I'm trying to change a variable value given to a component through props inside of a function in this component. I cannot get the value of the observable to change (even when passing the variable through parameter) so I wanted to know if I could retrieve the observable address to modify it directly this way.
@observer
class Exemple extends React.Component {
@observable Nom
@action onChangeNom = newValue => {
this.Nom = newValue //I want to have something similar to this function inside the component but it would take the value to update and the newValue as parameters
}
render() {
return (
<FormComponent //this is where I call my component
ContainerStyle={{
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
}}
ObjArray={[
{
InputDivStyle: { width: '49%', marginRight: '2%' },
FieldType: 'textInput',
FieldStyle: { borderColor: this.missingLastName ? 'red' : COLOR_NOT_BLACK },
OnChange: this.onChangeNom,
Placeholders: 'Ex. Durand',
Value: this.Nom, //this is the value I want to change inside the component
InputTitle: 'Nom',
},
]}
/>
)
}
}
@observer
class FormComponent extends React.Component<props> {
render() {
const { ObjArray, ContainerStyle } = this.props
return (
<div style={ContainerStyle}>
{ObjArray.map((e, index: number) => {
const { Disabled, FieldStyle, InputDivStyle, FieldType, Placeholders, OnChange, Value, InputTitle } = e
return (
<>
<div style={InputDivStyle ?? {}} key={index + 'Input'}>
{InputTitle && (
<>
<Label medium>{InputTitle}</Label>
</>
)}
<GenericInput
disabled={Disabled ?? false}
placeholder={Placeholders ?? ''}
style={FieldStyle ?? {}}
type={FieldType ?? ''}
value={Value ?? ''}
onChange={evt => {
OnChange(evt.target.value)
}}
/>
</div>
</>
)
})}
</div>
)
}
}
export default FormComponent
My concern is that I want to be able to change the value inside of the component without having to create a function for each value (if there was multiple objects in ObjArray for example. (I have already tried by passing the value as parameters inside of the component but it doesn't update it outside that's why I want to be able to change the value directly at the memory address where it is stored (like you can do in C with pointers)).
I want to be able to change the value directly at the memory address where it is stored
It is not possible in Javascript, you can't "pass-by-reference" (in original meaning) and so you can't change values like that.
The easiest way would be to have function like that:
@action onChange = (key, newValue) => {
this[key] = newValue
}
You pass it into component with a key and then invoke like that:
onChange={evt => {
// Or you can use InputTitle instead of key
OnChange(key, evt.target.value)
}}
That way you don't need to create lots of functions for every value