I have this ponent 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
?
I have this ponent 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
?
- You're gonna have to give us a little more info, and maybe format the question a little better. What exactly isn't working? Could you provide an example? – ZekeDroid Commented Feb 7, 2018 at 19:00
-
i have state prop called
title
i use this function and chnage the state based on the name of the input field and its value , my question is ... can this type of logic work for nested objects in state (e.g. salary.min) – Георги Димитранов Commented Feb 7, 2018 at 19:02
2 Answers
Reset to default 4Yes 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/docs/update.html
const salary = update(this.state.salary, {
min: minValue
});
this.setState({ salary });
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})
});