Answer the question
In order to leave comments, you need to log in
How to make controlled inputs with nested objects in state?
Good afternoon! An object is stored in state, inside of which there is another object:
name: '',
title: '',
fr: {
name: '',
title: ''
},
en: {
name: '',
title: ''
}
}
Answer the question
In order to leave comments, you need to log in
onChange = ({ target: { value, dataset: { objName, key } } }) => {
this.setState(({ [objName]: obj }) => ({
[objName]: {
...obj,
[key]: value,
},
}));
}
<input data-obj-name="fr" data-key="name" value={this.state.fr.name} onChange={this.onChange} />
<input data-obj-name="en" data-key="title" value={this.state.en.title} onChange={this.onChange} />
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question