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
    2.9K+ Learners
    4.52  (321)
    Heap Sort Program in C
    1 hrs
    Beginner
    1.3K+ Learners
    4.48  (42)
    Merge Sort Algorithm Using Java
    1 hrs
    Beginner
    1.2K+ Learners
    4.68  (28)
    Python IDE
    3 hrs
    Beginner
    3.4K+ Learners
    Searching Algorithms in Java
    2 hrs
    Beginner
    1.7K+ Learners
    4.65  (66)
    Graphs in Java
    2 hrs
    Intermediate
    2.4K+ Learners
    4.57  (53)
    Java Data Structures for Beginners
    3 hrs
    Beginner
    11K+ Learners
    4.58  (424)
    Java Data Structures for Intermediate Level
    3 hrs
    Intermediate
    6.6K+ Learners
    4.4  (183)