×

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 Props

    React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

    3 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 Table

    React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

    2 minutes read.

    Difference Between React Flux and MVC

    React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

    2 minutes read.

    React Lists

    React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

    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.

    React Component Life-Cycle

    React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

    4 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.

    React CSS

    What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

    5 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 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.

    React Flux

    React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

    2 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.

    Difference between Controlled and Uncontrolled component in ReactJs

    Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

    2 minutes read.

    React Refs

    React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

    7 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.

    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 Code Splitting

    React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

    4 minutes read.

    React Animation

    React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

    4 minutes read.

    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.