With 20+ yrs of industry experience in media, entertainment and web tech, Sachin brings expertise in hands-on training and developing forward-thinking, industry-centric curricula. 30k+ students have enrolled in his tech courses.
For enquiries call:
+1-469-442-0620
HomeBlogWeb DevelopmentWhat Are React Keys?
In React, lists are in the form of arrays in JavaScript which can store multiple values of the same data type. The general need to render lists of items in applications, whether they are web or mobile apps, is because the lists help in displaying the data in the ordered format. This is also mostly used to display the menus on the websites. In other words, lists focus on the UI part of the website, and are mainly used in displaying the menus on a website. Some examples of lists in a website are the navbar menu, sidebar menu etc.
In the normal JavaScript, the map () function is used to transverse the lists. In the code given below, the map () function is used to take the array of numbers and then multiply the elements of an array with 3. Here we declare a new array variable tripled, assign the new array values that are returned by the map () function and then log it.
Code
const number = [2, 4, 5, 3];
const tripled = number.map((num) => num * 3);
console.log(tripled)
Output : [6, 12, 15, 9]
While creating a list in React, the map() function is used to traverse the list elements and for updating the content in the lists. We use curly braces {} while working with lists in React.
The output obtained through the map() function is assigned to the listItem. We specify the order nature of the list in the output and return a <li> element for each item in the list. Finally, we render the React-DOM and obtain the result using the <ul> format at the end.
Here’s what the code looks like:
import React from 'react'; import ReactDOM from 'react-dom'; import reportWebVitals from './reportWebVitals'; // declaring the constants const myList = [1, 2, 3, 4, 5]; const listItems = myList.map((myList)=>{ return <div><li>{myList}</li></div>; }); // rendering using the ReactDOM, render() function ReactDOM.render( <ul> {listItems} </ul>, document.getElementById('root') ); reportWebVitals();
The line ReactDom.render() method is used to render a React element into the DOM in the supplied container and returns a reference to the component. In this, we are importing any App.js file or any Index.html file for rendering the pages. In the above example we are declaring variables and using the function in the same file itself using the root element.
Instead, we are using the “root” to point out the elements present in the index.ex.js file itself. The “root” element is the supplied container in DOM, and <ul>ListItem</ul> is the component. The root helps to auto render into the documents where it consists of Listelements to be printed out onto the console.
In the above example, we have initialized the list and rendered it using the map() function. We cannot render the list without using the “key” component. If we do so, we may get the output, but we may have some errors in the console. Consider the above example, which is coded without using the key component. In this case we have got the output, but the console has resulted in some warnings. So, it is suggested not to list the components in a program without the key component to uniquely identify the elements in the given list of elements.
In React, keys are like a Special String attribute that is included in the Creation of List of Elements. Keys play a great significance in React, and they help us to know what are the items in the given list of elements that have changed or are updated or removed. In simple words, the keys help in providing the identity to the elements in the Lists. Keys help to uniquely identify the elements in the Lists.
In general, the keys are declared using a flower brace “{}”, and in the braces the corresponding functionality is added to get the output of the program. Keys should be given to the elements that are present inside the array, to provide a stable entity to the elements. To pick the right key from the list, the element should be uniquely identified among the elements in the list.
Syntax: - key = { }
It is recommended to choose a STRING as a key, that identifies the items uniquely in a given list. If the given list contains the variable values as strings, and those strings are said to be unique, then the corresponding values can be taken as a KEY. Else if the given list doesn’t contain Strings for variable values, the corresponding variable is type-casted explicitly to strings and then used in the program.
By considering the problem encountered in the previous example, we try to remove the warnings using the Key attribute in the above program. After using the key attribute in the above example, we found there are no errors in the console, when we inspected the web page source. In this way the Key attribute is helpful to us in overcoming the errors in the creation of lists in React. The console is illustrated as below:
import React from 'react';
// creating a function
function Lists(){
const numbers = [1,2,3,4,5]
const listItems = numbers.map((number) => <li key={number.toString()}>{number}</li>)
return <div><ul>{listItems}</ul></div>
}
export default Lists;
import './App.css';
import Lists from './Lists';
import React from 'react';
// Defining the class named “App”
class App extends React.Component {
render() {
return (
<div className = "ml-2">
<h4>Usage of Keys resulted no Errors!</h4>
<Lists />
</div>
)
}
}
export default App;
import React from 'react';
// Creating the function using function keyword in react
function Lists(){
const stringLists = [ 'upgrad', 'knowledge', 'Hut', 'Blog', 'Writing'];
const updatedLists = stringLists.map((strList)=>
<li key={strList.id}> {strList} </li>)
return <div><ul>{updatedLists}</ul></div>
}
export default Lists;
import './App.css';
import Lists from './Lists';
import React from 'react';
// the class Name is defined here “App”
class App extends React.Component {
render() {
return (
<div className = "ml-2">
<h4>Usage of ID Form </h4>
<Lists />
</div>
)
}
}
export default App;
When we don’t have stable IDs for rendering of items, we use the item Index as the Key to access the elements in the list.
import React from 'react';
// defining the function
function Lists(){
const stringLists = [ 'bombay', 'delhi', 'calcutta' ];
const updatedLists = stringLists.map((strList, index)=>
<li key={index}> {strList} </li>)
return <div><ul>{updatedLists}</ul></div>
}
export default Lists;
import './App.css'; import Lists from './Lists'; import React from 'react'; // class Name is defined here class App extends React.Component { render() { return ( <div className = "ml-2"> <h4>Usage of INDEX Form </h4> <Lists /> </div> ) } } export default App;
It is not recommended to use the Indexes for the KEYS, if there is change in the order of items. That action sometimes may result in negative performance and could cause some issues with the Component State.
Keys are generally used to identify the unique element in the given list of elements. But, the usage of keys while mapping to the elements describes a particular order. Assigning of keys creates an order and structure that leads to the correct implementation.
For example, let us imagine we have created ListItem as a separate component and that ListItem is used for extraction of elements in the list of elements. In this case we should assign the Key component to the <ListItem /> in the given array of elements but not to the <li /> component present in the ListItem itself.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
function ListItem(props) {
const item = props.item;
return (
// Wrong Usage
<li key={item.toString()}>
{item}
</li>
);
}
function NameList(props) {
const myLists = props.myLists;
const listItems = myLists.map((strLists) =>
// Key should be used here
<ListItem item={strLists} />
);
return (
<div>
<h2>Incorrect Key Usage Example</h2>
<ol>{listItems}</ol>
</div>
);
}
const myLists = ['csk', 'rcb', 'mi', 'srh', 'kkr', 'dd'];
ReactDOM.render(
<NameList myLists={myLists}/>,
document.getElementById('root')
)
reportWebVitals();
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>REACT TEST</title> </head> <body> <div id="root"></div> <script src="./index.js"></script> </body> </html>
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function ListItem(props) { const item = props.item; return ( // key is not written here <li> {item} </li> ); } function NameList(props) { const myLists = props.myLists; const listItems = myLists.map((strLists) => // Key is written here <ListItem key={myLists.toString()} item={strLists} /> ); return ( <div> <h2>Correct Key Usage Example</h2> <ol>{listItems}</ol> </div> ); } const myLists = ['HYD', 'MYS', 'AP', 'GOA']; ReactDOM.render( <NameList myLists={myLists}/>, document.getElementById('root') ) reportWebVitals();
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>REACT TEST</title> </head> <body> <div id="root"></div> <script src="./index.js"></script> </body> </html>
While working with usage of Key with Component, we mostly work on two files namely the JavaScript file (“index.js”) and the HTML file (“index.html”). At this time, we don’t have any work to do with the App.js file, so we comment out the code lines in the file and work only on the index JavaScript and HTML files.
The usage of keys in both the examples demonstrated above results in a similar output. But if there is any incorrect usage of keys, we come across errors in the corresponding HTML page on inspection. If the key is used correctly, there will not be any errors if we inspect the page.
We had learnt that the key should be unique among all the elements in the given list of elements i.e., it should be unique among the siblings in the given list. It is not compulsory that the keys initialized in the program should be Globally unique. We will try to produce two different arrays using the same set of keys as demonstrated below:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function TourBlog(props) { const place = ( <ol> {props.data.map((show) => <li key={show.id}> {show.title} </li> )} </ol> ); const famousfor = props.data.map((show) => <div key={show.id}> <h3>{show.title}: {show.content}</h3> </div> ); return ( <div> {place} <hr /> {famousfor} </div> ); } const data = [ {id: 1, title: 'Goa', content: 'Famous For Beaches.....!!'}, {id: 2, title: 'Mumbai', content: 'Famous For Street Food.........!!'}, {id: 3, title: 'Manali', content: 'Famous for Valleys & Beautiful Scenaries....!!'} ]; ReactDOM.render( <TourBlog data={data} />, document.getElementById('root') ); reportWebVitals();
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>REACT TEST</title> </head> <body> <div id="root"></div> <script src="./index.js"></script> </body> </html>
Looking to master Python? Dive into our comprehensive full course on Python language full course. Unlock the power of coding with Python and unleash your creativity. Start your journey today!
To sum up what we have learnt in this article:
We can access the key elements using the Id and Index forms.
We can use keys along with the Components. In this, we assign the Key component with the respective <ListItem> only, but not to the <li> component unless the particular item type is not specified in the given program.
Finally, we have seen the usage of Key component with two types of arrays in the given program itself to generate the result at the end.
Name | Date | Fee | Know more |
---|