×

React Keys

React Keys

A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful when working with the dynamically created components or whenever the users updated the list. It helps to determine the components in a collection that requires to be re-rendered rather than to re-render the entire set of components every time.

Keys should be in the array for providing a stable identity to elements.

Example:

const num = [ 1,2,3,4]; 
const updatedNum = num.map((number)=>{ 
  • {number}
  • ; });

    If there is no stable ID for rendered items, then you can assign the indexes of the array as a key to the list items. It can be clear in the following example:

    Example:

    const num = [ 1,2,3,4]; 
    const updatedNum = num.map((number, index)=>{ 
    
  • {number}
  • ; });

    It is highly dissatisfied to assign array indexes as keys because it can be possible that array elements can be reordered in the future. And if the order of the element gets changed, then their key will also change; that's why it will be confusing for a developer. It also creates issues with the state of the component.

    Using Keys with Components

    Consider a case in which you create a separate component for the list items, and you are extracting the items of the list from that component. In this case, you have to assign the keys to that component in which you are returning from the iterator instead of assigning them to the list items. That means you have to assign keys to <component/> instead of <li>. It is to keep in mind that anything in which you are returning from inside of the map() function, you need to assign a key.                                                                                                                                   

    Example:

    Incorrect Key Usage

    import React from 'react'; 
     import ReactDOM from 'react-dom'; 
     function List(props) { 
      const item = props.item; 
      return ( 
      // Wrong format for specifying the key here. 
      
  • {item}
  • ); } function Name(props) { const myLists = props.myLists; const items = myLists.map((strLists) => // The key should have been specified here. ); return (

    Incorrect Key Usage Example

      {items}
    ); } const myLists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa']; ReactDOM.render( , document.getElementById('app') ); export default App;

    Output:

    React Keys

    Example:

    Correct Key Usage

    For correcting the above code, we have to assign a key to the map() iterator.

    import React from 'react'; 
     import ReactDOM from 'react-dom'; 
     function List(props) { 
      const item = props.item; 
      return ( 
      //Should not specify the key here.
      
  • {item}
  • ); } function Name(props) { const myLists = props.myLists; const listItems = myLists.map((strLists) => // The key should have been specified here. ); return (

    Correct Key Usage Example

      {listItems}
    ); } const myLists = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa']; ReactDOM.render( , document.getElementById('app') ); export default App;

    Output:

    Correct Key Usage

    There is an example that shows the dynamic creation of Content elements having a unique index (id) are given below. The Key value should be unique for every element, so we are assigning id as a key for each element that is created.

    Example:

    import React from 'react';
     class App extends React.Component {
      constructor() {
      super();
      this.state = {
      item:[
      {
      listItem: 'Akash', 
      id: 1
      },
      {
      listItem: 'Aman',
      id: 2
      },
      { 
      listItem: 'Anup',
      id: 3
      }
      ]
      }
      }
      render() { 
      return (
      
    {this.state.item.map((dynamicComponent, id)=> )}
    ); } } class Example extends React.Component { render() { return (

    Name={this.props.componentData.listItem}
    id={this.props.componentData.id}

    ); } } export default App;

    Output:

    Correct Key Usage

    It is to be noted that Keys are not like as props, only the way of assigning the key to a component is similar to props. Keys are internal to React, and they cannot be accessible from inside the component like props.


    Related Topics

    React Higher-Order Components

    React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

    2 minutes read.

    React Constructors

    What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

    4 minutes read.

    React Portals

    React Portals React portals were introduced by React 16.0 in September 2017. It gives you a way to render the element outside of the component hierarchy, i.e., within a separate component. Before React 16.0, it...

    3 minutes read.

    Difference Between State and Props in React

    Comparison between State and Props State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over...

    2 minutes read.

    React Fragments

    React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

    2 minutes read.

    React Keys

    React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

    3 minutes read.

    ReactJS vs AngularJS

    Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

    5 minutes read.

    React Error Boundaries

    React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

    3 minutes read.

    React Map

    React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

    2 minutes read.

    How to use React Context

    React Context React Context is used to pass the data through the component tree without passing the props down manually at the every level. In React Application, the data is passed in a top-down approach...

    4 minutes read.

    Comparison between React and Vue

    Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

    3 minutes read.

    ReactJS Versions

    ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

    4 minutes read.

    React JSX

    React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

    3 minutes read.

    React Environment Setup Step by Step

    React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

    5 minutes read.

    React Events

    React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

    2 minutes read.

    React Components

    React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

    2 minutes read.

    React Native vs ReactJS

    Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

    6 minutes read.

    Pros and Cons of ReactJS

    Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

    3 minutes read.

    Features of ReactJS

    ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

    2 minutes read.

    React Hooks

    React Hooks The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes....

    5 minutes read.