React Lists and Keys

Back to home
Logicmojo - Updated Aug 28, 2021



React Lists

When it comes to building a website's user interface, lists are extremely beneficial. Lists are most commonly used to display menus on a website, such as the navbar menu. Arrays can be used to create lists in normal JavaScript. In React, we can make lists in the same way that we can in normal JavaScript. In this article, we'll go over how to do that in more depth.
Let's look at how to explore and update any list in ordinary JavaScript first. For traversing lists, we can utilise JavaScript's map() method.

The traversal of lists is done with the map() function. The map() function the values of an array of numbers added to 10 in the example below. We report the new array provided by map() and put it to the variable multiplyNums.

Example :

    var arr = [10, 20, 30, 40, 50];   
    const add10 = arr.map((number)=>{   
        return (number + 10);   
    });   
    console.log(arr10);   



Output :

[20, 30, 40, 50, 60]


Let's look at how to make a list with React. To do this, we'll use the map() method to traverse the list element, and we'll surround updates in curly braces. Finally, the array elements are assigned to listItems. Put this new list inside the ul>/ul> elements and render it to the DOM.


Example :

    import React from 'react';   
    import ReactDOM from 'react-dom';   
      
    const List = ['Sahil', 'Sameer', 'Kiran', 'Ruhi', 'Uresh'];   
    const items = List.map((List)=>{   
        return <li>{List}</li>;   
    });  
    
    ReactDOM.render(   
        <ul> {items} </ul>,   
        document.getElementById('app')   
    );   
    export default App;  



Output :

Sahil
Sameer
Kiran
Ruhi
Uresh


Rendering Lists inside components

We rendered the list to the DOM directly in the React code above. However, rendering lists with React is usually not a smart idea. We've already discussed the benefits of components and seen how everything in React is made up of distinct components. Take, for example, a Navigation Menu. The items in a navigation menu are obviously not hard programmed on any website. This item is retrieved from the database and shown in the browser as lists. So, from the perspective of the component, we can say that we'll use props to send a list to a component, and then use this component to render the list to the DOM. We can replace the above code, which produced the list directly, with a component that takes an array as a prop and returns an unordered list.


import React from 'react';   
import ReactDOM from 'react-dom';   
function List(props) {  
  const Lists = props.Lists;  
  const items = Lists.map(List) =>  
    <li>{List}</li>  
  );  
  return (  
    
<ul>{listItems}</ul>
); } const Lists = ['Suman', 'Arpit', 'Kunal', 'Rohit', 'Umang']; ReactDOM.render( , document.getElementById('app') ); export default App;



Output :

Suman
Arpit
Kunal
Rohit
Umang


React uses keys to keep track of elements. If an item is updated or removed, only that item, not the entire list, will be re-rendered.
Each sibling's key should be different. They can, however, be reproduced globally.


Above code using keys concept :

import React from 'react';   
import ReactDOM from 'react-dom';   
function List(props) {  
  const Lists = props.Lists;  
  const items = Lists.map(List) =>  
    <li>{List}</li>  
  );  
  return (  
    
<ul>{Lists.map((List) => )}</ul>
); } const Lists = [{id : 1, name: 'Suman'}, {id : 2, name: 'Arpit'}, {id : 3, name: 'Kunal'}, {id : 4, name: 'Rohit'}, {id : 5, name: 'Umang'}]; ReactDOM.render( , document.getElementById('app') ); export default App;



Why do we need keys for React lists?

When we use the.map() function to loop through an element or a component, we must give a unique value to the key prop.
It would look like this if we were mapping over an element:


temps.map(temp => <li key={temp.id}>{temp.title}</li>)



If we're mapping over a component, it could look like this:


temps.map(temp => <li key={temp.id}>{temp.title}</li>)



In all cases, we must include a key with a unique value, or React will alert us.

Why? Because keys inform React about which element or component in a list is which.

If we tried to change the order of the items in this list by inserting more or editing them in any manner, React wouldn't know what to do.
This is because React handles all of the DOM updates for us (via a virtual DOM), yet keys are required for React to update the DOM appropriately.


React keys

A key is a one-of-a-kind identifier. It's used by React to determine which List items have changed, been updated, or been removed. It is beneficial when we have added components dynamically or when users change the lists. It also aids in determining which components in a collection need to be re-rendered rather than rendering the complete collection each time.
The most effective way to choose a key is to think of it as a string that uniquely identifies the items in the list.

const arrs = [ 10, 20, 30, 40, 50 ];
const updatedArr = arr.map((arrs)=>{
return <li key={index}>{ arrs } </li>;
});



The array indexes can also be used as keys for the list elements. The elements in the following example are given array indexes as keys.


const arr = [ 10, 20, 30, 40, 50 ];
const updatedArr = arr.map((arrs, index)=>{
return <li>{ arrs } </li>;
});



If the order of items may change, we don't advocate utilising indexes as keys. This can have a detrimental influence on performance and cause component state difficulties.


Using Keys with Components

Assume you've constructed a second ListItem component and you're extracting ListItem from that component. In this scenario, the keys should be assigned to the array's ListItem /> elements rather than the ListItem's li> elements. Keep in mind that keys only make sense in the context of the surrounding array to prevent making mistakes. As a result, anything returned by the map() function should be given a key.


Incorrect Usage

function List(props) {
  const value = props.value;
  return (
    <li key={value.toString()}> {value}
    </li>
  );
}

function NumList(props) {
  const num = props.num;
  const listItems = num.map((x) =>
     <List value={x} />  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}




Correct Usage

function List(props) {
  const value = props.value;
    return <li>{props.value}</li>;
}

function NumList(props) {
  const num = props.num;
  const listItems = num.map((x) =>
        <List key={num.toString()} value={num} />
  return (
    <ul>
      {listItems}
    </ul>
  );
}



As a general rule, components inside the map() method require keys.

Uniqueness of Keys among Siblings

We had previously explored how array keys must be unique among their siblings. This does not, however, imply that the keys must be globally unique. We can make two separate arrays with the same set of keys. In the sample below, you can see how it works.


Example :

function fun(props) {
  const sidebar = (    <ul>
      {props.temp.map((t) =>
        <li key={t.id}> {t.title}
        </li>
      )}
    </ul>
  );
  const content = props.posts.map((post) =>    <div key={post.id}>      <h3>{post.name}</h3>
    </div>
  );
  return (
    <div>
      {sidebar}    
    </div>
  );
}

const temp = [
  {id: 1, name: 'Harshit'},
  {id: 2, name: 'Ishita'},
  {id: 3, name: 'Karan'}
];

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<fun temp={posts} />);



React uses keys as a hint, but they aren't supplied to your components. If your component requires thae same value, pass it as a prop with a different name.


const content = temp.map((t) =>
  <temp
    key={t.id}    id={t.id}    name={t.title} />
);



Conclusion: So there you have it, your journey into the React Lists and Keys.