Search code examples
reactjsstatesetstate

React set state with variable that is nested


I have an input that looks like

<input name="data.company.name" value="Bob's Burgers" />

and on it's onChange I'd like to update the state with it's name.

<input name="data.company.name" value="Bob's Burgers" onChange={(e) => this.setState({ [e.name]: e.target.value}) />

But when I do this the state looks like

this.state = {
   data: { company: { name: '' } },
   data.company.name: "Bob's Burgers"
}

How can I achieve passing the name to the state so I end up with

this.state = {
   data: { company: { name: "Bob's Burgers" } }
}

I cannot alter the name of the input as it's set via a Field Component.


Solution

  • If you don't mind adding lodash to your project you could do this:

    <input
      name="data.company.name"
      value="Bob's Burgers"
      onChange={e =>
        e.persist();
        this.setState(prevState => {
          return _.setWith(_.clone(prevState), e.name, e.target.value, _.clone);
        });
      }
    />;