React JS Keys and Index

Each child in an array or iterator should have a unique 'key' prop.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file. We have one list component as a parent component and one country component as a child component.

1. List

List
import React from 'react'; import country from './country'; function List() { const contries = [ { id : 1, name : 'India', continent : 'Asia' }, { id : 2, name : 'Brazil', continent : 'South America' }, { id : 3, name : 'Nepal', continent : 'Asia' }, { id : 4, name : 'Maxico', continent : 'North America' } ]; const countryList = contries.map((country)=> <country country={country} /> ); return ( <div> {countryList} </div> } } export default List;

2. country

country
import React from 'react'; function country( { name, continent }) { return <h1>{name} is in {continent}<h1> } export default country;

When we run the above code, it will give a console error. Each child in an array or iterator should have a unique 'key' prop. So, in the List component when we call Country component, we have to assign unique key props.

Example
const countryList = contries.map((country)=> <country key={country.id} country={country} /> );

Here, we can also give the key to the country.name. make sure that it should be unique within the list. Also, we can't take as a prop in the child components.

Why key is required?

Let's take list without key

List A

  • India
  • China

when we add a new item in it

  • Brazil
  • . Then react read the first item if not match then go to the second item if not match then add the third item in the list. In this way, it will check through the list. When react hasĀ a key then it matches the child key in a subsequent tree and react know the key 3 is a new one and it inserted into the list. it reduces the complexity of execution.

    Example
    function List() { const contries = [ { name : 'India', continent : 'Asia' }, { name : 'Brazil', continent : 'South America' }, { name : 'Nepal', continent : 'Asia' }, { name : 'Maxico', continent : 'North America' } ]; return ( <div> { contries.map((country)=> return <h1>{country.name} is in {country.continent}<h1> ) } </div> } }

    In this way, we can show object list in browser, we can also, take '

    <h1>{contry.name} is in {contry.continent}<h1>' in child component and put child component's name in countries.map code. Also, we can use array.map for show data in table format or grid format.

    Summary

    • Keys give the elements a stable identity.
    • Keys help react identify which items have changed, are added, or are removed.
    • Help inefficient update of the user interface.

     

    ← Previous

    Next →