More

    React Key Defined: Usage, Components and Alternatives

    An Introduction to React Key:

    A key refers to a special string attribute that needs to be included while creating lists of elements in React. 

     

    Why are Keys used in React? 

    These Keys are used in React in order to identify which items in the list are changed, updated, or deleted. 

    In simpler words, keys are used to give an identity to the elements on the list. 

    It is highly recommended that a string key that uniquely identifies the items in the list is used with react. Given below are some examples of string keys:

     

    const numbers = [ 1, 2, 3, 4, 5 ]; 

      

    const updatedNums = numbers.map((number)=>{ 

    return <li>{ number } </li>; 

    }); 

     You can also assign array indexes as key to the list items. Given below is an example where an array index is assigned as a key to the elements. 

     

    const numbers = [ 1, 2, 3, 4, 5 ]; 

      

    const updatedNums = numbers.map((number, index)=>{ 

    return <li>{ number } </li>; 

    }); 

     

    It is important to note that assigning keys is highly discouraged because if the elements of the arrays get reordered in the future it will get confusing for the developer as the keys for the elements will also change. 

     

    Using React Keys with Components- 

    Take a situation where you have created a separate component for the list item and are extracting the list items from the component. In this case, you will have to assign keys to the component you are returning from the iterator and not to the list items. 

    This means, you should assign react keys. To <Component/> and not to <li>. A good practice in order to avoid mistakes is to remember that anything you are returning from inside of map() function is needed to be assigned a key. 

     

    Here is an example of incorrect usage of keys.

     

    import React from ‘react’; 

    import ReactDOM from ‘react-dom’;

      

    // Component to be extracted 

    function MenuItems(props)

        const item = props.item; 

      

            return(

                <li>

                    {item}

                </li>    

            );

       

    // Component that will return an 

    // unordered list 

    function Navmenu(props)

            const list = props.menuitems; 

      

        const updatedList = list.map((listItems)=>{ 

                return

                      

            );

        }); 

       

        return( 

            <ul>{updatedList}</ul>);

       

    const menuItems = [1, 2, 3, 4, 5]; 

       

    ReactDOM.render( 

        ,  

        document.getElementById(‘root’)

    ); 

     

    Output: 

    It can be seen in the above image output that the list is rendered successfully but a warning is thrown to the console that the elements inside the iterator are not assigned keys. This is because we had not assigned key to the elements we are returning to the map () iterator. 

     

    Given below is an example of the correct usage of keys: 

    import React from ‘react’; 

    import ReactDOM from ‘react-dom’;

      

    // Component to be extracted 

    function MenuItems(props)

        const item = props.item; 

      

            return(

                <li>

                    {item}

                </li>    

            );

       

    // Component that will return an 

    // unordered list 

    function Navmenu(props)

            const list = props.menuitems; 

      

        const updatedList = list.map((listItems)=>{ 

                return

                      

            );

        }); 

       

        return( 

            <ul>{updatedList}</ul>);

       

    const menuItems = [1, 2, 3, 4, 5]; 

       

    ReactDOM.render( 

        ,  

        document.getElementById(‘root’)

    ); 

     

    The code above will run successfully and efficiently without any warning message. 

     

    The uniqueness of Keys with React: 

    While talking about keys, we have discussed multiple times that keys assign to the array element must be unique. By this we did not mean that the keys should be globally unique. All the elements in a particular array should have unique keys. That is, two different arrays can have the same set of keys. 

     

    In the code given below, we have created two different arrays namely menuitems1 and menuitems2. It can be seen by these codes that the keys for the first 5 items for both arrays are the same, the code still runs successfully without any warning. 

     

    import React from ‘react’; 

    import ReactDOM from ‘react-dom’;

      

    // Component to be extracted 

    function MenuItems(props)

        const item = props.item; 

      

            return(

                <li>

                    {item}

                </li>    

            );

       

    // Component that will return an 

    // unordered list 

    function Navmenu(props)

            const list = props.menuitems; 

      

        const updatedList = list.map((listItems)=>{ 

                return

                      

            );

        }); 

       

        return( 

            <ul>{updatedList}</ul>);

       

    const menuItems1 = [1, 2, 3, 4, 5]; 

    const menuItems2 = [1, 2, 3, 4, 5, 6]; 

       

    ReactDOM.render( 

        <div>

              

              

        </div>, 

        document.getElementById(‘root’)

    ); 

     

    Note: Keys and props are not similar. Only the process and method of assigning a key to a component is same as that of props. Keys are internal to React and cannot be accessed from inside of the component like props. Therefore, we can use the same value we have assigned to the Key for any other prop we are passing to the component. 

     

     Another alternative to Extracting Components with React Keys: 

     Keys only make sense in the context of the surrounding array. 

     For example, if you extract a ListItem component, you should keep the key on the <ListItem/> elements in the array rather than on the <li> element in the ListItem itself. 

     

    function ListItem(props) {

      const value = props.value;

      return (

        // Wrong! There is no need to specify the key here:

        <li key={value.toString()}>

          {value}

        </li>

      );

    }

     

    function NumberList(props) {

      const numbers = props.numbers;

      const listItems = numbers.map((number) =>

        // Wrong! The key should have been specified here:

        <ListItem value={number} />

      );

      return (

        <ul>

          {listItems}

        </ul>

      );

    }

     

    const numbers = [1, 2, 3, 4, 5];

    ReactDOM.render(

      <NumberList numbers={numbers} />,

      document.getElementById(‘root’)

    );

      

    Example of correct usage of keys

     

    function ListItem(props) {

      // Correct! There is no need to specify the key here:

      return <li>{props.value}</li>;

    }

     

    function NumberList(props) {

      const numbers = props.numbers;

      const listItems = numbers.map((number) =>

        // Correct! Key should be specified inside the array.

        <ListItem key={number.toString()} value={number} />

      );

      return (

        <ul>

          {listItems}

        </ul>

      );

    }

     

    const numbers = [1, 2, 3, 4, 5];

    ReactDOM.render(

      <NumberList numbers={numbers} />,

      document.getElementById(‘root’)

    );

     

     

    A good rule of thumb is that elements inside the map() call need keys. 

     

    Keys Must Only Be Unique Among Siblings- 

     Keys used within arrays should be unique among their siblings. However, they don’t need to be globally unique. We can use the same keys when we produce two different arrays: 

     

     

    function Blog(props) {

      const sidebar = (

        <ul>

          {props.posts.map((post) =>

            <li key={post.id}>

              {post.title}

            </li>

          )}

        </ul>

      );

      const content = props.posts.map((post) =>

        <div key={post.id}>

          <h3>{post.title}</h3>

          <p>{post.content}</p>

        </div>

      );

      return (

        <div>

          {sidebar}

          <hr />

          {content}

        </div>

      );

    }

     

    const posts = [

      {id: 1, title: ‘Hello World’, content: ‘Welcome to learning React!’},

      {id: 2, title: ‘Installation’, content: ‘You can install React from npm.’}

    ];

    ReactDOM.render(

      <Blog posts={posts} />,

      document.getElementById(‘root’)

    );

     Key serve as a hint in React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name: 

     

    const content = posts.map((post) =>

      <Post

        key={post.id}

        id={post.id}

        title={post.title} />

    );

     With the example above, the Post component can read props.id, but not props.key.

     

     

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here