I have an array in the state and want to change the array depending on the index here is the method I use
dynamicFieldsOnChange(e, index) {
this.setState({[product_colors[index]]: e.target.value});
};
But it's not working any idea why?
I have an array in the state and want to change the array depending on the index here is the method I use
dynamicFieldsOnChange(e, index) {
this.setState({[product_colors[index]]: e.target.value});
};
But it's not working any idea why?
Directly updating state value using
this.state[e.target.id] = e.target.value
is a bad practice. You should always avoid that.
Instead, you should do something like this,
this.setState({[e.target.id] : e.target.value});
This will set id in a local state.
You need to get the previous state first, using prevstate callback event. if you want to retain all the elements of an array . spread the prevState . then call the product_colors then pass the modified array.
Like this:
dynamicFieldsOnChange(e,index)
{
this.setState( (prevState) => {
prevState.product_colors[index] = e.target.value
return{
...prevState,
product_colors: [...prevState.product_colors]
}
});
};