Updated March 27, 2023
Introduction to React Keys
Key in React js is used to identify uniquely to an item, especially in the case of dynamic react component it will be very useful to identify dynamic components and it is also used when we wanted to identify the change in an item like the update, delete, etc.
Syntax:
Below is a very simple syntax to use the key to react js. Here below syntax we are calling a component A and passing some dynamic data along with the unique key. Because of this unique id which we are passing in the form of key to its parent component, it will be uniquely identified.
<"A(any component)" key = {uni1ue id} Data = {dynamic data for component A}/>
Why do we need Keys React?
There are a few important reasons why we need Keys in react they are:
If your code contains repetitive time which we need to do again and again for various arrays of data, in that case, react keys will be very helpful. It will allow us to create the same components with passing unique key and with this our HTML code will get shorter. Many times when we will be creating any dynamic components, at that time it is possible that we wanted to track changes in a component like if anything updated, deleted in the component.
With the help of a unique key value, we can identify the changes. Also if in case you want to control the rendering of components, because it may be possible that there may be many components but we only wanted to render few components, in general, if we wanted to control the rendering of the components than with the help of key we can decide which components should be renders.
In this way, we will be able to design a well perform react component, as the only the required components are getting renders. React js dynamic components are very successful only because of the keys. Because without keys even we will be able to create dynamic components but if we can not differentiate between many dynamic components that were generated from the same components will be of no use.Because we can not perform uniquely activity on the components. It gives us the power to reduce the size of code for generating many components from one with the help of keys concepts
Examples to implement the use of React Keys
Given below are the examples of the following Keys:
Example #1
Creating a class with name “dynamic component” which will extend react core component, this component contains a state which consists data array of object with components. A new component will be called again and again in DynamicComponent class and it will get a new uniqueId. Because of this unique id in the key section, we will be able to uniquely identify our components. Exporting the main class component for external uses.
Whoever wants to use this component they can extend this class. The main difference here from any normal component is we have written only for once to the component NewComponent and this component is getting called inside the component DynamicComponent for each value of data array. As we are running map function over state data array and passing each id in the form of key to make component unique. please see the below example for understanding.
Work perform buy DynamicComponent,
- This is the main component that will be first called, and inside it, we are calling another new component called NewComponent and passing dynamic data and key.
- In the component NewComponent we are getting props from parent DynamicComponent and from array data and key it will produce the dynamic components.
Code:
class DynamicComponent extends React.Component {
constructor() {
super();
this.state = {
data:[
{
component: '1st Component',
id: 1
},
{
component: '2nd Component',
id: 2
},
{
component: '3rd Component',
id: 3
}
]
}
}
render() {
return (
<div>
<div>
{this.state.data.map((data, uniqueId) => <NewComponent
key = {uniqueId} data = {data}/>)}
</div>
</div>
);
}
}
class NewComponent extends React.Component {
render() {
return (
<div>
<div>{this.props.data.component}</div>
<div>{this.props.data.id}</div>
</div>
);
}
}
export default DynamicComponent;
Example #2
This is a very simple example where we are passing key in the form of string numeric (“1”, “2”). Here we are not using any components. We are using these keys with normal HTML tag P and passing keys. Please see the example below along with the output of the example.
Code:
const App = props => [
<p key="1">React key simple example</p>,
<p key="2">Render array of elements</p>
];
ReactDOM.render(
<App />,
document.querySelector("#root")
);
<div id="root"></div>
Output:
Example #3
Here we are creating dynamic components with add or remove button events.
Inside components App:
- We have created a function getInitialState which initializing the initial values for the initial number of components and names and a unique id for buttons.
- handleClick function is performing click add or remove event
- Calling component DynamicComponent each time with change value.
- View component called to pass change count of the component.
Inside Dynamic Component:
- Getting all change instructions from its parent component App.
Inside View:
- Each time it gets the count and push the new item and return it.
- It is the function that is creating a component with a unique key on each call.
Code:
var App = React.createClass({
getInitialState: function(){
return {
count : 8,
activityButton: [
{name: "remove", id: 1},
{name: "add", id: 2}
]
}
},
handleClick: function(event){
switch (event.target.id) {
case "1":
this.state.count === 1 ?
this.setState({count: 1}) :
this.setState({count : this.state.count -1});
break;
case "2":
this.setState({count : this.state.count + 1});
break;
case "3":
break;
}
},
render: function() {
return (
<div>
<h3>generate or remove components</h3>
<DynamicComponent activityButton ={this.state.activityButton} onClick = {this.handleClick}/>
<View count={this.state.count}/>
</div>
)
}
});
var DynamicComponent = React.createClass({
render: function() {
return (
<div onClick={this.props.onClick}>
{this.props.activityButton.map(function(activityButton){
return <button type="button" id= {activityButton.id} >{activityButton.name}</button>
})}
</div>
)
}
});
var View = React.createClass({
render: function() {
var comp = [];
for (var j = 0; j < this.props.count; j++) {
comp.push(<div key={j}>{j+1}</div>);
}
return (<div>{comp}</div>);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);
<div id="root"></div>
Output:
Conclusion
From this tutorial, we learned that react js keys are very useful to create unique components and give us the power to identify them.
Recommended Articles
This is a guide to React Keys. Here we discuss the introduction to React Keys along with the need and its respective examples. You can also go through our other related articles to learn more–