What are lists and keys in React, the basics that every frontend developer should know to create an awesome software

Duomly - Dec 21 '20 - - Dev Community

This article was originally published at https://www.blog.duomly.com/list-and-keys-in-react/


List and keys in React intro

List and keys in React are among the most basic concepts. It may be the first scary one for beginners who just started to create their first application using the React framework.

And what's even scarier, you can't avoid using lists because almost every application has some kind of repeatable content.
But in reality, really simple. It just needs to be explained.

That's why in this article, I decided to explain what lists are, how to build a list in JSX, what keys are and how to fix one of the most common errors connected to list and keys you will see a lot of times in your console.

This article will be a complete cheat sheet about lists and keys in React, so make sure you'll save it in your favorites to come back when you need to remind something.

As always, for those who prefer to watch instead of reading, I encourage you to visit our Youtube channel to find a video version of this article.

Let's start!

List in React

Showing a list of elements happened almost in every project I was ever writing. And React really simplifies the rendering of lists inside the JSX by supporting the Javascript .map() method.

The .map() method in Javascript iterates through the parent array and calls a function on every element of that array. Then it creates a new array with transformed values. It doesn't change the parent array.

Now, let's imagine that you are creating a simple Todo App. The main element of your project will be a list of tasks. To show them, you will need data, which in most cases will be an array of elements, can be objects or strings, for example.
While you have the array with data, you can use the .map() method inside the JSX component the transform the data into the element.

Let's take a look at the graphic and code.

const tasks = [
  {text: "Buy flowers", status: "todo"},
  {text: "Go to the dentist", status: "done"},
]
const tasksList = tasks.map(task => {
  return (
  <p>{task.text} - {task.status}</p>
  )
});
Enter fullscreen mode Exit fullscreen mode

List and keys in ReactYou can see how we transform the data given as the array of simple objects to the JSX component in the image.

List in React

Instead of the simple JSX element, you can use any other component and pass the values from the array as the props.
I hope it's clear now how to create a list in React's JSX component. Now, let's find out what the keys are and why we are talking about them in this article.

Keys in React

When creating a list of elements in a way you can see above, there's one more necessary thing, and it's a key.

key is a special attribute that you need to include in the element, and it should be a string. Keys in each list should be unique, which means that you shouldn't use values that can be the same as the key. In other words, keys should be unique among the siblings, not globally.

For example, you should not use status or text as a key in our example.

Key is kind of the id for the element, and it helps React to identify which element was changed, added, or removed.

It's a good practice to select a value that is a unique identifier for an item in the array, commonly it's the ID.
Let's modify our example.

const tasks = [
  {id: "1", text: "Buy flowers", status: "todo"},
  {id: "3", text: "Go to the dentist", status: "done"},
]
const tasksList = tasks.map(task => {
  return (
  <p key={task.id}>{task.text} - {task.status}</p>
  )
});
Enter fullscreen mode Exit fullscreen mode

Keys in React

Keys in ReactIn the above code, I used the id of each task to identify my list item. In this case, it's already a string, but if it wouldn't be, we should transform it with .toString() method.

But it may also happen that you don't have any id or any other unique value which can be used. Then, there is another solution that allows you to use index.

const tasks = [
  {text: "Buy flowers", status: "todo"},
  {text: "Go to the dentist", status: "done"},
]
const tasksList = tasks.map((task, index) => {
  return (
  <p key={index}>{task.text} - {task.status}</p>
  )
});
Enter fullscreen mode Exit fullscreen mode

It is possible, and it's even what React does by default if you don't pass the key, but it's not a recommended solution, especially if you want to manipulate the elements and, for example, change their position.

Considering that key is the only thing that allows React to identify the element in the DOM, and if you'd add or remove an element, and the index will still be there as the key, React may not realize that the component actually changed.

Using index in the key may bring you troubles, break the application, or display wrong data, and that's what you want to avoid.

So, should you or shouldn't you use index as a key in your project?

There are three conditions which you need to check, and all of them have to be met to be able to use index as a key in your list with a clear conscience:

  • you never order or filter the list
  • you never do any change or computing on the list or list items
  • items of the list have no ids

Great, you know a lot about the keys right now, so let's check how you can generate unique keys if you don't have them in your data.

How to generate unique keys React?

Suppose the data you are using doesn't have unique values like ids or any other identifier, and you desperately need to use a different value than the index. In that case, there are at least two ways to do it.

  • Generate the key by yourself

You can create a simple Javascript function that will generate a random number or string. Also can use new Date().getTime() Javascript methods to generate a random number, add any prefix and, use it as your key.

  • Use an existing plugin

There are a few ready solutions for generating unique keys for React lists. The one I use very often is shortid with it's generate() method. The other recommended ones are uuid and uniqid. All of them are pretty simple to install and use.
Great! I hope that solves almost all of the problems with lists and keys in React.

Each child in a list should have a unique "key" prop

The last point I'd like to mention in this article is about the most common and persistent error you will see in the console during the development.

If you see the following error Each child in a list should have a unique key prop…, you know that the only solution is to actually add a unique key to each of your list items.

Even if you already assigned the key and you still see the error, it may mean that any of the keys is not unique. To solve that, you need to use one of the solutions described above to make sure your key value is unique.

Summary

In this article, I explained to you how to generate a list in React JSX, what keys are, and why it's essential to add them.
You also found out about the methods you can use to generate the unique ids and why key uniqueness is important in some cases.

I hope you'll find this guide useful, especially as a beginner in ReactJS or frontend development at all.

If you'd like to learn about React Component Lifecycle, take a look at the previous video in our blog. And to create your first application with a list, join our React JS tutorial.

Programming courses online

Thank you for reading,
Anna from Duomly

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player