English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ReactJS Keys

keysReact is very useful when using dynamically created components or when the user changes the list. SetkeyThe value will keep the changed component with a unique identifier.

Using Keys

Let us dynamically create Content elements with a unique index (i). The map function will create three elements from the data array. Since the key value must be unique for each element, we will assign i as the key for each created element.

App.jsx

import React from 'react';
class App extends React.Component {
   constructor() {}}
      super();
      this.state = {
         data:[
            {
               component: 'First...',
               id: 1
            },
            {
               component: 'Second...',
               id: 2
            },
            {
               component: 'Third...',
               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'));

For each element's key value, we will get the following result.

If we add or remove some elements in the future or change the order of dynamically created elements, React will use thesekeyTo track each element by value.