Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change state of nested object props based on user input handleChange

I have this component state

this.state = {
      title: "",
      salary: {
        min: "",
        max: "",
        single: ""
      }
}

I use this function for handling user input

handleInputChange = (e) => {
    this.setState({[e.target.name]:e.target.value});
}

it works with

<input type="text" id="title" name="title" onChange={this.handleInputChange}/>

Can I use such a function to change this.state.salary.min/max ...

I mean can this type of function work with nested objects in state and <input/> name art?

like image 334
Георги Димитранов Avatar asked Feb 07 '18 18:02

Георги Димитранов


People also ask

How do I change state in React nested object?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

How do you change the state of an object?

State can hold any kind of JavaScript value, including objects. But you shouldn't change objects that you hold in the React state directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy.

How do you update part of state in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state. When the state has been updated, our component re-renders automatically.


1 Answers

Yes you can, but you need to update whole nested object.

You have several options:

Object.assign()

const salary = Object.assign({}, this.state.salary, { min: minValue });

this.setState({ salary });

Spread operator

const salary =  {
    ...this.state.salary,
    min: minValue
}

this.setState({ salary });

Immutable data structure

Immutable.js

this.state = {
    salary = Immutable.Map({ 
        min: 8,
        max: 10
    });
};

const salary = this.state.salary.set('min', minValue);

this.setState({ salary });

Immutability helper

See https://reactjs.org/docs/update.html

const salary = update(this.state.salary, {
    min: minValue
});

this.setState({ salary });
like image 169
Zlo Bae Avatar answered Sep 30 '22 18:09

Zlo Bae