Open In App

ReactJS Keys

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React JS keys are a way of providing a unique identity to each item while creating the React JS Lists so that React can identify the element to be processed.

What is a key in React ?

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted.

Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.  

Assigning keys to the list

You can assign the array indexes as keys to the list items. The below example assigns array indexes as keys to the elements. 

Syntax:

const numbers = [1, 2, 3, 4, 5];
const updatedNums = numbers.map((number, index) =>
<li key={index}>
{number}
</li>
);

Issue with index as keys

Assigning indexes as keys is highly discouraged because if the elements of the arrays get reordered in the future then it will get confusing for the developer as the keys for the elements will also change.

Difference between keys and props in React

Keys are not the same as props, only the method of assigning “key” to a component is the same as that of props. Keys are internal to React and can not 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.

Using Keys with Components :

Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case, you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to <Component /> and not to <li> A good practice to avoid mistakes is to keep in mind that anything you are returning from inside of the map() function is needed to be assigned a key.  

Incorrect usage of keys:

Example 1: The below code shows the incorrect usage of keys:

Javascript




import React from "react";
import ReactDOM from "react-dom/client";
// Component to be extracted
function MenuItems(props) {
    const item = props.item;
    return <li key={item.toString()}>{item}</li>;
}
 
// Component that will return an
// unordered list
function Navmenu(props) {
    const list = props.menuitems;
    const updatedList = list.map((listItems) => {
        return <MenuItems item={listItems} />;
    });
 
    return <ul>{updatedList}</ul>;
}
const menuItems = [1, 2, 3, 4, 5];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Navmenu menuitems={menuItems} />
  </React.StrictMode>
);


Output:  You can see in the below 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 the key to the elements we are returning to the map() iterator.

Correct usage of keys:

Example 2: The below example shows the correct usage of keys.

Javascript




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 <MenuItems key={listItems.toString()} item={listItems} />;
    });
 
    return <ul>{updatedList}</ul>;
}
 
const menuItems = [1, 2, 3, 4, 5];
 
ReactDOM.render(
    <Navmenu menuitems={menuItems} />,
    document.getElementById("root")
);


Output: In the below-given output you can clearly see that this time the output is rendered but without any type of warning in the console, it is the correct way to use React Keys.

Uniqueness of Keys:

We have told many times while discussing keys that keys assigned to the array elements 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.

Example 3: In the below code, we have created two different arrays menuItems1 and menuItems2. You can see in the below code that the keys for the first 5 items for both arrays are the same still the code runs successfully without any warning. 

Javascript




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 <MenuItems key={listItems.toString()} item={listItems} />;
    });
 
    return <ul>{updatedList}</ul>;
}
 
const menuItems1 = [1, 2, 3, 4, 5];
const menuItems2 = [1, 2, 3, 4, 5, 6];
 
ReactDOM.render(
    <div>
        <Navmenu menuitems={menuItems1} />
        <Navmenu menuitems={menuItems2} />
    </div>,
    document.getElementById("root")
);


Output: This will be the output of the above code



Previous Article
Next Article

Similar Reads

How to hide your API keys from public in ReactJS?
An API (Application Programming Interface) key is a unique identifier used to authenticate a user, developer, or calling program to an API. However, they are typically used to authenticate a project with the API rather than a human user. And while using the online services many times, these keys get into the wrong hands, which can be very dangerous
2 min read
ISRO original papers and official Keys
Download links for previous years ISRO original Papers and official Keys: Original Paper Official Keys ISRO 2018 ISRO 2018 Key ISRO 2017 Dec ISRO 2017 Dec Key ISRO 2017 May ISRO 2017 May Key ISRO 2016 ISRO 2016 Key ISRO 2015 ISRO 2015 Key ISRO 2014 ISRO 2014 Key ISRO 2013 ISRO 2013 Key ISRO 2011 ISRO 2009 ISRO 2008 ISRO 2007
1 min read
JavaScript Array keys() Method
The Javascript array.keys() method is used to return a new array iterator which contains the keys for each index in the given input array. Syntax: array.keys() Parameters: This method does not accept any parameters. Return Values: It returns a new array iterator. The below example illustrates the Array keys() method in JavaScript: Example 1: In thi
2 min read
JavaScript typedArray.keys() Method
The typedArray.keys() is an inbuilt function in JavaScript which is used to return a new array iterator containing the keys for each index of the elements of the given typedArray. Syntax: typedArray.keys() Parameter: This function does not accept anything as parameter. Return value: It returns a new array iterator object containing the keys for eac
1 min read
Merge two arrays keeping original keys in PHP
Problem: How to merge two arrays while keeping keys instead of reindexing in PHP? Solution: This can be achieved in two ways which are by using + operator and by using inbuilt functions. Method 1: Using + operator. Example : &lt;?php $array1 = array( 1 =&gt;'Geeks', 2 =&gt;'For', 3 =&gt;'Geeks' ); $array2 = array( 4 =&gt; 'A', 5 =&gt; 'Computer', 6
1 min read
PHP | Ds\Map keys() Function
The Ds\Map::keys() function of PHP is used to get a set of keys of the current Map instance. The order of keys in the returned set is the same as that of the order of keys in the actual Map instance. Syntax: Ds\Set public Ds\Map::keys ( void ) Parameter: This function does not accepts any parameter. Return value: It returns a set of Ds\Set containi
1 min read
Reset keys of array elements using PHP ?
In PHP, two types of arrays are possible indexed and associative array. In case of Indexed array, the elements are strictly integer indexed and in case of associative array every element has corresponding keys associated with them and the elements can only be accessed using these keys. To access the keys and values of an associative array using int
3 min read
API Keys and their security
After having so much discussion about API Keys and OAuth Credential, in this article, we will focus on which one is better from security and privacy point of view. But before proceeding further let's first recall what does Authentication and Authorization means? Authentication means to validate your identity by using credentials like User Id, Usern
4 min read
Node.js URLSearchParams.keys()
In URLSearchParams interface, the keys() method returns an Iterator which allows us to iterate through all the keys present in the object. Syntax: searchParams.keys(); Return:Returns an ES6 Iterator over the names of each name-value pair. Example 1: var searchParams = new URLSearchParams(&quot;keyA=valueA&amp;keyB=valueB&quot;); // Display the key/
1 min read
D3.js | d3.keys() Function
The d3.keys() function in D3.js is used to return an array containing the property names or keys of the specified object or an associative array. Syntax: d3.keys(object) Parameters: This function accepts single parameter object containing key and value in pairs. Return Value: It returns the keys of the given object. Below programs illustrate the d3
1 min read
Practice Tags :