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

    File Manipulation in Python
    1 hrs
    Beginner
    1.3K+ Learners
    4.22  (37)
    Regex in Python
    1 hrs
    Beginner
    2.1K+ Learners
    4.31  (87)
    Heap Sort Program in C
    1 hrs
    Beginner
    1.1K+ Learners
    4.56  (32)
    Python Jobs
    2 hrs
    Beginner
    2.4K+ Learners
    4.52  (50)
    Merge Sort Algorithm Using Java
    1 hrs
    Beginner
    917 Learners
    4.56  (18)
    Python IDE
    3 hrs
    Beginner
    1.7K+ Learners
    Searching Algorithms in Java
    2 hrs
    Beginner
    1.4K+ Learners
    4.69  (29)
    Graphs in Java
    2 hrs
    Intermediate
    1.9K+ Learners
    4.53  (32)
    Java Data Structures for Beginners
    3 hrs
    Beginner
    9.3K+ Learners
    4.54  (231)
    Java Data Structures for Intermediate Level
    3 hrs
    Intermediate
    5.5K+ Learners
    4.46  (122)