DEV Community

SavvyShivam
SavvyShivam

Posted on

2 1

Keys in React

Keys in React

Introduction to Keys

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to uniquely identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.

Below is the updated code with keys:

This code will give the same output as that of the previous code(demonstrated in the List module) but this time without any warning. Keys are the most useful when we create components dynamically or when there is alteration of any sort in the list.

Using Keys in Components

Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case, you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to and not to “li” tag. A good practice to avoid mistakes is to keep in mind that anything you are returning from inside of the map() function is needed to be assigned a key.

MenuItems is the component to be extracted.

Navmenu is the component that will return an unordered list.

Output

The code above can be found in the link given below:

https://codesandbox.io/s/keys-in-comp-qbuoks

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay