Home >>ReactJS Tutorial >ReactJS Keys

ReactJS Keys

ReactJS Keys

A key is a single identifier. It is used in React to identify which items from the Lists have changed, updated, or deleted. It's useful when we build components dynamically, or when users alter the lists. It also helps to determine the components need to be re-rendered in a series, rather than re-rendering the entire set of components each time.

Keys should be given within the array to provide a stable identity for the elements. The best way to pick a key as a string that identifies the items in the list in a unique way. Can be understood with the example below.

Example


const stringLists = [ 'One', 'Two', 'Three', 'Four', 'Five' ];    
const updatedLists = stringLists.map((strList)=>{   
    <li key={strList.id}> {strList} </li>;   
});  

Example


const stringLists = [ 'One', 'Two', 'Three', 'Four', 'Five' ];   
const updatedLists = stringLists.map((strList, index)=>{   
    <li key={index}> {strList} </li>;   
}); 

Using Keys with component

Suggest creating a separate ListItem component, and removing ListItem from that object. You should in this case assign keys to the <ListItem/> elements in the array, not to the <li> elements in the ListItem itself. To prevent errors, it is important to keep in mind that keys make sense only in the context of the surrounding array. So it is recommended that everything that you return from the map() function is assigned a key.

Example: Incorrect Key usage


import React from 'react';

class App extends React.Component 
{
   constructor() {
      super();
    
      this.state = {
         data:[
            {
               component: 'One',
               id: 1
            },
            {
               component: 'Two',
               id: 2
            },
            {
               component: 'Three',
               id: 3
            }
         ]
      }
   }
   render() {
      return (
         <div>
            <div>
               {this.state.data.map((dynamicComponent, i) => <Content 
                  key = {i} componentData = {dynamicComponent}/>)}
            </div>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <div>{this.props.componentData.component}</div>
            <div>{this.props.componentData.id}</div>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

Output:

ReactJS Keys


No Sidebar ads