Reputation: 1309
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
Reputation: 167
Yes you can, but you need to update whole nested object.
You have several options:
const salary = Object.assign({}, this.state.salary, { min: minValue });
this.setState({ salary });
const salary = {
...this.state.salary,
min: minValue
}
this.setState({ salary });
this.state = {
salary = Immutable.Map({
min: 8,
max: 10
});
};
const salary = this.state.salary.set('min', minValue);
this.setState({ salary });
See https://reactjs.org/docs/update.html
const salary = update(this.state.salary, {
min: minValue
});
this.setState({ salary });
Upvotes: 4
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