I have the following snippet of code:
onChange(e) {
e.persist
this.setState((prevState) => {
prevState[e.target.id] = e.target.value
return prevState
})
}
the how would i set the state for each key using something like the code above.
this is the initial state:
this.state = {
heading: this.props.match.params.length > 1 ? "Edit Post" : "Create Post",
title: '',
category: '',
body: '',
author: ''
}
Basic rule is:
We can use Computed property names concept and use any js expression to compute the object property name dynamically. For that we need to put the expression inside []
.
Like this:
var obj = {
[10 * 20 + 1 - 5]: "Hello"
};
console.log('obj = ', obj);
Solution:
As per the code you posted, you need to put e.target.id
inside []
, like this:
onChange(e) {
this.setState({
[e.target.id]: e.target.value
})
}
Or we can create that object first, then pass that object to setState
function, like this:
onChange(e) {
let obj = {};
obj[e.target.id] = e.target.value
this.setState(obj);
}
Also you don't need the prevState
. You can directly update the state variable with new value.prevState
is required only when new state value is dependent on previous state value, like in case of counter.
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