4 years ago
Zaid Bin Khalid
2,330 Views
3
In this session, we will talk about react JS keys along with codes and examples.
React JS keys.
A key can be described as a special identifier. In React JS key is used to identify the items from the lists that have changed, deleted, and updated. Keys should have a stable identity in the elements. A simple example is given below.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);
React JS Using Keys.
Through unique index (i), we dynamically create Content elements. From our data array, the map() function will create three elements. Since the key-value for every element needs to be unique. Here, we will allocate i as a key for every created element.
//App.jsx
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data:[
{
component: 'First...',
id: 1
},
{
component: 'Second...',
id: 2
},
{
component: 'Third...',
id: 3
}
]
}
}
render() {
return (
<div>
<div>
{this.state.data.map((dynamicComponent, i) => <Content
key = {i} componentData = {dynamicComponent}/>)}
</div>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<div>{this.props.componentData.component}</div>
<div>{this.props.componentData.id}</div>
</div>
);
}
}
export default App;
The main.js file code is below.
//main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
The following result of above given key values of each element is:
To keep track of each element, React will use the key values. So, if any element added or removed in the future or any changes in the order occurred the keys will dynamically create elements.
4 years ago
Zaid Bin Khalid
2,330 Views
3