In this tutorial you will learn about the ReactJS Keys and its application with practical example.
ReactJS Keys
In React, keys are helpful when we are dealing with a collection of components or elements. Assigning key to an element or component allows React to uniquely identify it when it has changed, added, or removed. Keys can be assigned to individual elements inside the map() function.
Example:-
Step 1:- Let’s open src/App.js, delete the existing code and put the following code in it and save it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import React, { Component } from 'react'; class App extends React.Component { constructor() { super(); this.state = { employees:[ { empName: 'John', id: 1 }, { empName: 'Steve', id: 2 }, { empName: 'Alex', id: 3 } ] } } render() { return ( <div> <h1>W3Adda - React Keys</h1> <div> {this.state.employees.map((data, i) => <Employee key = {i} empData = {data}/>)} </div> </div> ); } } class Employee extends React.Component { render() { return ( <div> <div>{this.props.empData.empName}</div> <div>{this.props.empData.id}</div> </div> ); } } export default App; |
Step 2:- Let’s open the terminal again, change directory to your project folder and type the following command in order to run the server.
1 |
npm start |
Step 3:- Now open the following URL in browser to view the output
http://localhost:3000
Step 4:- You will see the following screen.