React JS

ReactJS - Keys

ReactJS - Keys

Keys are used for keeping track of individual components within collections so that they can be identified easily and manipulated efficiently without causing unnecessary duplication or confusion among elements. 

Here is an example of a list of items that have unique keys: 

import React, { Component } from 'react'; 
class MyList extends Component { 
render() { 
const items = [ 
{ id: 1, text: 'Item x' }, 
{ id: 2, text: 'Item y' }, 
{ id: 3, text: 'Item z' }, 
]; 
return ( 
<ul> 
{items.map(item => ( 
<li key={item.id}>{item.text}</li> 
))} 
</ul> 
); 
} 
} 
export default MyList; 

In this example, the list of items is rendered using the map function. Each item has a unique id property that is used as the key. The key is passed to the li element using the key attribute. 

A key should be 
● unique among its siblings 
● stable and predictable 

It is not recommended to have an array index as a key as they are not identifiers since the index changes when an element is added or removed from the array.Instead, you should use a unique identifier that is stable and predictable, such as the item's ID or unique property. 
 

Top course recommendations for you

    Regex in Python
    1 hrs
    Beginner
    3.1K+ Learners
    4.53  (395)
    Heap Sort Program in C
    1 hrs
    Beginner
    1.4K+ Learners
    4.58  (55)
    Merge Sort Algorithm Using Java
    1 hrs
    Beginner
    1.2K+ Learners
    4.7  (47)
    Python IDE
    3 hrs
    Beginner
    3.7K+ Learners
    Searching Algorithms in Java
    2 hrs
    Beginner
    1.8K+ Learners
    4.7  (98)
    Graphs in Java
    2 hrs
    Intermediate
    2.5K+ Learners
    4.53  (79)
    Java Data Structures for Beginners
    3 hrs
    Beginner
    11.2K+ Learners
    4.57  (461)
    Java Data Structures for Intermediate Level
    3 hrs
    Intermediate
    6.7K+ Learners
    4.4  (212)