ReactJS | Lists and Keys Tutorial with Example

ReactJS Lists and Keys Tutorial with Example

Hello ReactJS Friends,

Lists and Keys in React are the most common concepts used for almost every ReactJS Application. Let’s learn about lists and Keys in ReactJS with examples.

Lists and Keys in ReactJS

A “key” is a special string attribute. Keys must be included when creating lists of elements in React.

Uses of Keys in ReactJS

  • Keys are used in React to identify which items have been changed, updated, or deleted from the list.
  • It also helps to determine which components need to be rerendered instead of rerendering the whole set of components.
  • Keys are used to give an identity to the elements in the lists.

The next thing that comes to mind is what should be good to be chosen as the key for the items in the lists. Using a string as a key that uniquely identifies the items in the list is recommended.

Example:

The below example shows a list with string keys.

const numbers = [ 1, 2, 3, 4, 5 ];
 
const updatedNums = numbers.map((number)=>{
return <li key={index}>{number} </li>;
})

We can also assign the array indexes as keys to the list items.

const numbers = [ 1, 2, 3, 4, 5 ];
 
const updatedNums = numbers.map((number, index)=>
<li key = {index}>
{number}
</li>
);

Output:

SS 1

When we set the key in any tag with the ‘key’ keyword, the error of the key prop is gone.

function App()
{
    const menuItems = [1, 2, 3, 4, 5];
    return (
        <div className="App">
        <header className="App-header">
        {
            menuItems.map(el => {
                return <div key={el}>{el}</div>
            })
        }
        </header>
        </div>
    );
}

Output:

lists and keys

Conclusion:

This was all about Lists and Keys in ReactJS. Hope the examples mentioned above will help you better understand Lists and Keys in React. Hire ReactJS Developers for all your development needs.

Share the tutorial with your other RectJS friends, and stay in touch with us for more tutorials on ReactJS.

Happy Coding!

Previous Article

Laravel | Working with Blade Template Engine

Next Article

15 Best Magento 2 Extensions to Boost your Business in 2024

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨