MOCKSTACKS
EN
Questions And Answers

More Tutorials









React use of Keys


Keys in react are used to identify a list of DOM elements from the same hierarchy internally.

So if you are iterating over an array to show a list of li elements, each of the li elements needs a unique identifier specified by the key property. This usually can be the id of your database item or the index of the array.

Using the id of an element


Here we are having a list of todo items that is passed to the props of our component. Each todo item has a text and id property. Imagine that the id property comes from a backend datastore and is a unique numeric value:

todos = [
 {
 id: 1,
 text: 'value 1'
 },
 {
 id: 2,
 text: 'value 2'
 },
 {
 id: 3,
 text: 'value 3'
 },
 {
 id: 4,
 text: 'value 4'
 },
];


We set the key attribute of each iterated list element to todo-${todo.id} so that react can identify it internally:

render() {
 const { todos } = this.props;
 return (
 <ul>
 { todos.map((todo) =>
 <li key={ `todo-${todo.id}` }>
 { todo.text }
 </li>
 }
 </ul>
 );
}

Using the array index


If you don't have unique database ids at hand, you could also use the numeric index of your array like this:

render() {
 const { todos } = this.props;
 return (
 <ul>
 { todos.map((todo, index) =>
 <li key={ `todo-${index}` }>
 { todo.text }
 </li>
 }
 </ul>
 );
}


Conclusion

In this page (written and validated by ) you learned about React use of Keys . What's Next? If you are interested in completing React tutorial, your next topic will be learning about: React Higher Order Components.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.