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?

Upvotes: 5

Views: 2424

Answers (2)

Zoltan Kovac
Zoltan Kovac

Reputation: 167

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 });

Upvotes: 4

Aaditya Thakkar
Aaditya Thakkar

Reputation: 1820

Yes, you can do that by using spread operator in setState.

this.setState(prevState => ({
    ...prevState,
    salary: {
        ...prevState.salary,
        min: newMinValue
    }
}))

Or, you can use Object.assign() if you are using ES5.

this.setState({
  salary: Object.assign({}, this.state.salary, {min: newMinValue})
});

Upvotes: 3

Related Questions