Reputation: 2496
I have an array of items stored in this.state.items
and user can add/remove items by clicking buttons which modify this.state.items
.
I have something like this. (This code is untested, and may not compile, but you probably get the idea.)
TextField = React.createClass({
render() {
return <input type="text"/>;
}
});
TextList = React.createClass({
getInitialState () {
return {
items: [<TextField />, <TextField />, <TextField />]
};
},
addItem() {
// Adds a new <TextField /> to this.state.items
},
removeItem(index) {
// Filters out the item with the specified index and updates the items array.
this.setState({items: this.state.items.filter((_, i) => i !== index)});
},
render() {
return (
<ul>
{this.state.items.map((item, index) => {
return (
<li key={index}>
{item}
<button onClick={this.props.removeItem.bind(null, index)}>Remove</button>
</li>
);
})}
</ul>
<button onClick={this.addItem}>Add New Item</button>
);
}
});
This can remove the specified item in the this.state.items
. I saw it in console, and this part is working properly. But that's not what is presented to the user.
For example, if there are 3 input fields, and user types "One", "Two", and "Three" respectively, then if he clicks on the remove button for "Two", the input field with "Three" is removed instead. In other words, always the last field is removed.
How can I fix this so that the value of the input fields are properly associated with the removed ones?
Upvotes: 0
Views: 121
Reputation: 14101
This is because react recycles items based on their key, for speed and efficiency. Using an index that always is 0,1,2 etc therefore has unwanted consequences.
How react works:
Solution: make the key unique to the specific item. Better to base on item content.
Upvotes: 1