Since it's an an array you want to modify you can use array indices. Suppose the initial state is this.
this.state = {
array: [{
name: 3,
value: 1000
},{
name: 5,
value: 1000
}]
}
Then the inputs can be like this (for the one with name 3 which has index 0)
<input value={this.state.array[0].value} onChange={this.handleChange.bind(this,0)}/>
So the value it will display is for the 1st element in the array (with index 0) and the handleChange
binds to the event
as well as pass the index 0.
handleChange(index,event){
this.setState((prevState) => ({array:[
...prevState.array.slice(0, index),
Object.assign({},prevState.array[index],{value:event.target.value}),
...prevState.array.slice(index + 1)
]}))
}
Ok so this might seem a little complicate but let me try to explain here. So the handleChange
method takes two parameters - the event
corresponding to the input text and the index
which is the array index of the element in the state array (0 in our example). So in this.setState
we have taken the prevState
and used a bit of splicing. ...prevState.array.slice(0,index)
corresponds to all elements of the array before the one we are modifying. ...prevState.slice(index+1)
corresponds to all those after. So we take these two sets and join them with the modified element in between. The Object.assign()
corresponds to the modified element. What it is doing is taking the prevState.array[index]
which is the element we are modifying and setting it's value
to event.target.value
corresponding to the text.