Reputation: 43
I have an onChange function to update the state on all of my form inputs. The state I'm trying to update here is nested in an array as an object, but I am unsure how I can make a reusable function that will update the specific object property depending on which form input is changed.
Here's my function:
onChangeHandler = (e, index) => {
let currentStateObject = [...this.state.fundGroups]; //copying the current state
// This works, but I don't want allocationName to be hardcoded.
// How can I pass in a variable that relates to the specific property
// based on which input field is changed?
currentStateObject[index].allocationName = e.target.value;
this.setState({
currentStateObject
});
}
Here is what I have attempted but it does not work and breaks my code with an invalid token message:
currentStateObject[index].[e.target.name] = e.target.
I attempted this because in my input field, I added name="allocationName"
Does anyone know if I'm close to solving this? I'm very new to React. Thank you.
Upvotes: 3
Views: 289
Reputation: 3248
here is some example of state manipilation
state = {
random: [],
counter: 1
}
stateHandler = (e)=>{
let oldrandom = [...this.state.random]
oldrandom[e.target.name] = e.target.value;
this.setState({random:oldrandom })
}
manipulate state with a functional approach
stateHandler = ()=>{
this.setState((state,props)=>{
counter: state.counter+props.increment
})
}
Upvotes: 1
Reputation: 1592
You can simply:
onChangeHandler(event) {
this.setState({ [event.target.name]: event.target.value })
}
Upvotes: 1
Reputation: 576
you almost got it. simply remove the .
between [index]
and [e.target.name]
like:
currentStateObject[index][e.target.name] = e.target.value;
Upvotes: 3