Blog Details

img
Data Science

How do you give keys in React

Spoke Right / 14 Nov, 2023

React Keys
A key is a unique identifier which is used to identify which items have changed, updated, or deleted from the Lists and to determine which components in a collection needs to be re-rendered.

Using Keys with the component:

Example: Incorrect usage of the Key.

import React from 'react';   
import ReactDOM from 'react-dom';   
function CityList(props) {  
const city = props.city;  
return (  
//Specifying the key here is a wrong practice.  
  • {city}
  • ); } function CityNames(props) { const citylist = props.citylist; const cityname = citylist.map((strLists) => // Specifying the key here is a right practice. ); return (

    Incorrect Key Usage

    1. {cityname}
    ); } const citylist = ['Jaipur', 'Jodhpur', 'Udaipur', 'Pune', 'Chandigarh']; ReactDOM.render( , document.getElementById('app') ); export default App;

Output:

1. Jaipur
2. Jodhpur
3. Udaipur
4. Pune
5. Chandigarh

Example: Correct usage of the Key.

function CityList(props) {  
const city = props.city;  
return (  
//Specifying the key here is a wrong practice.  
  • {city}
  • ); } function CityNames(props) { const citylist = props.citylist; const cityname = citylist.map((strLists) => // Specifying the key here is a right practice. ); return (

    Correct Key Usage

    1. {cityname}
    ); } const citylist = ['Jaipur', 'Jodhpur', 'Udaipur', 'Pune', 'Chandigarh']; ReactDOM.render( , document.getElementById('app')

Output:

1. Jaipur
2. Jodhpur
3. Udaipur
4. Pune
5. Chandigarh

The uniqueness of Keys among Siblings:

In an array, the keys assignment must be unique among their siblings. However, we can use the same set of keys in producing two different arrays.

Example:

import React from 'react';   
import ReactDOM from 'react-dom';   
function Menulist(props) {  
const Names = (  
  1. {props.info.map((show) =>
  2. {show.name}
  3. )}
); const remark = props.info.map((show) =>

{show.name}: {show.remark}

); return (
{name}
{remark}
); } const info = [ {id: 10, name: 'Joy', remark: 'Good!!'}, {id: 20, name: 'Happy', remark: 'Excellent!!'}, {id: 30, name: 'Smiley', remark: 'Keep Going!!'} ]; ReactDOM.render( , document.getElementById('app') ); export default App;

0 comments

Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0