S
S
Sanchik972020-06-18 09:06:31
React
Sanchik97, 2020-06-18 09:06:31

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:

spoiler
name: '',
 title: '',
  fr: {
    name: '',
                title: ''
  },
  en: {
    name: '',
                title: ''
  }
}


How to hang an onChange event on the input so that at the same time it changes the value of the name or title key inside, for example, the en object

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-18
@Sanchik97

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 question

Ask a Question

731 491 924 answers to any question