'Get and change a key value inside an object inside the state react js
I have an object inside my state and I want to be able to grab it and change it, I'm trying to use spread syntax but it's not working:
handleChange = (e) => {
this.setState({
...this.state, postData: [this.state.postData.email, e.target.value]
})
}
this is how I'm trying but apparently something its wrong
Solution 1:[1]
Assumed objective:
To use handleChange method and update different props within a nested state object.
Example: update steps and email in the below state object:
this.state = {
initialMSG: '',
initialPos: 0,
initialMove: 0,
initialCoord: 0,
postData: { 'x': 2, 'y': 2, 'steps': 0, 'email': '' }
};
Code Snippet
This below code snippet may provide one possible solution to achieve the assumed/desired objective:
class Thingy extends React.Component {
constructor(props) {
super(props);
this.state = {
initialMSG: '',
initialPos: 0,
initialMove: 0,
initialCoord: 0,
postData: { 'x': 2, 'y': 2, 'steps': 0, 'email': '' }
};
this.handleChange = this.handleChange.bind(this);
};
handleChange = e => {
const obj = {[e.target.name]: e.target.value};
console.log('updating postData: ', obj);
this.setState(
prev => ({
...prev,
postData: {
...prev.postData,
...obj
}
})
);
};
render() {
const { steps, email } = this.state.postData;
return (
<div>
Steps:
<input value={steps} onChange={this.handleChange} name='steps' />
<br/>
Email:
<input value={email} onChange={this.handleChange} name='email' />
</div>
);
}
};
ReactDOM.render(
<div>
DEMO
<Thingy />
</div>,
document.getElementById('reactDiv')
);
<div id='reactDiv' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Explanation
- The
handleChangemethod accepts the eventeas the parameter - The two
<input />elements forstepsandemailboth havename - When the values change, the same
handleChangeis triggered - However, for
stepsthename(ie, thee.target.name) will bestepsand foremailit will beemail - This distinction is used to update the relevant prop within
postData
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jsN00b |
