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
?
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.
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.
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With