What are List and Keys in React?

Subscribe to my newsletter and never miss my upcoming articles

In JavaScript, if you want to create a new array from an available array by converting each element of the original array to create the corresponding element of the new array, you can use map() method.

Keys help React distinguish items in a list. It helps React manage the changed items, new items added, or items removed from the list.


We can output lists JavaScript arrays and the map() function. The map() is used to traverse through an array. Below basic list component that accepts an array of number and outputs a list of elements.

function Numberlist (props) {
    const numbers = props.numbers; 
    const listItems = numbers.map((number) => 
       <li key={number.toString()}>{ number }</li>
     ); //listItems becomes a list of numbers (or an array of 5 <li> tags)
     return (
     <ul>{ listItems }</ul>
     ); 
}
const numbers = [1, 2, 3, 4, 5]; 
ReactDOM.render(
     <NumberList numbers={numbers} />, 
     document.getElementById('root')
);

A key is a special string attribute you need to include when creating lists of elements, as you must have also seen in the last slide. Keys help React identify which items have changes, are added, or are removed. Keys should be given to the elements a stable identity.

When you don't have stable IDs or a suitable property to be used as key for the rendered items, you may use the item index as a key as last resort:

const todoItems = todos.map((todo, index) => 
     <li key={index}>
       { todo.text }
     </li>
);

📘Thanks For Reading | Happy Coding ⚡

No Comments Yet