×

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

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

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

    What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

    10 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 Bootstrap

    React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

    9 minutes read.

    React State

    React 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 time. The change...

    3 minutes read.

    React Conditional Rendering

    React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

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

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

    ReactJS Tutorial

    ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

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