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.7K+ Learners
    4.38  (154)
    Heap Sort Program in C
    1 hrs
    Beginner
    1.3K+ Learners
    4.44  (39)
    Merge Sort Algorithm Using Java
    1 hrs
    Beginner
    1.1K+ Learners
    4.65  (26)
    Python IDE
    3 hrs
    Beginner
    3.3K+ Learners
    Searching Algorithms in Java
    2 hrs
    Beginner
    1.7K+ Learners
    4.51  (39)
    Graphs in Java
    2 hrs
    Intermediate
    2.4K+ Learners
    4.55  (51)
    Java Data Structures for Beginners
    3 hrs
    Beginner
    10.8K+ Learners
    4.51  (330)
    Java Data Structures for Intermediate Level
    3 hrs
    Intermediate
    6.5K+ Learners
    4.4  (176)