// noprotect
class Item extends React.Component {
render() {
return (
<div className="form-group">
<label className="col-xs-4 control-label">{this.props.name}</label>
<div className="col-xs-8">
<input type='text' className='form-control' />
</div>
</div>
)
}
}
class Example extends React.Component {
constructor() {
super();
this.state = {
list: [
{name: 'Foo1444610101010', id: 1444610101010},
{name: 'Bar1444600000000', id: 1444600000000}
]
};
}
userInput() {
const firstItems = Array.from(document.querySelectorAll('.form-group:first-child input'));
firstItems.forEach((item) => item.value = 'It is ' + (new Date()).toTimeString())
}
addItem() {
const id = +new Date;
this.setState({
list: [ {name: 'Baz' + id, id} , ...this.state.list]
});
}
render() {
return (
<div>
<b>How to use: </b>
First write something in the inputs
(or <a href='#' onClick={this.userInput}>simulate it</a>).
Then hit <em>Add item</em> and see what happens…
<hr/>
<button className='btn btn-primary' onClick={this.addItem.bind(this)}><b>Add item</b> to the beginning of the list</button>
<h3>Dangerous <code>key=index</code></h3>
<form className="form-horizontal">
{this.state.list.map((todo, index) =>
<Item {...todo}
key={index} />
)}
</form>
<h3>Better <code>key=id</code></h3>
<form className="form-horizontal">
{this.state.list.map((todo) =>
<Item {...todo}
key={todo.id} />
)}
</form>
<hr/>
<a href='https://medium.com/p/e0349aece318'>« Back to the article</a>.
</div>
)
}
}
I have this source code here, displaying the difference between adding a unique key to react components in an array vs adding an index key to react components in an array. It seems that the value on the input is moving to the newest react component in the case of an index key. Whereas in the case of a unique key, the value of the input stays in position. I think the e-rendering of an array of react components with unique and index keys is different. The value of the input is not being saved, so during re-render how come its value is maintained?
How does the react algorithm work for re-renders of arrays?
Wander verse is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.