DEV Community

Cover image for Lists and Keys
Bipin Rajbhar
Bipin Rajbhar

Posted on

Lists and Keys

Rendering a list of items is very common in any Application.

If we render a list of items like this, then there is no problem.

function FruitsList() {
  return (
    <ul>
      <li>apple</li>
      <li>banana</li>
      <li>grapes</li>
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

If we render a list of items as an array, which very common in React.

const fruits = ['apple', 'banana', 'grapes'];

function FruitsList() {
  return (
    <ul>
      // returns an array of React Element
      {fruits.map(fruit => <li>{fruit}</li>)}
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

It will generate the same HTML, but with a warning.

Alt Text

We can interpolate an Array of renderable elements in React, but it has interesting implications when things change over time.

If you rerender that list with an added item, React does not really know whether an item is added at the beginning, middle, or end of the list. And the same goes for the removed items.

Example 1

If you remove the items from the end then it will work as expected but, if you remove items from the start or middle it will behave a little bit differently.

key prop

The key prop helps React to identify where the elements have changed, are added, or are removed.

const fruits = [{id: 'apple', value: 'apple'}, {id: 'banana' value: 'banana'}, {id: 'grapes', value: 'grapes'}];

function FruitsList() {
  return (
    <ul>
      // returns an array of React Element
      {fruits.map(fruit => <li key={fruit.id}>{fruit.value}</li>)}
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

Without key vs with array index as key vs with a proper key.

Example 2

The behavior of React Element without key is the same as with an array index as a key.

I hope you learned something from this article and if you have any doubts, please leave a comment. I will be delighted to answer all of your questions.

My name is Bipin Rajbhar and I am a software engineer at QuikieApps, and you can follow or connect to me on Twitter and Linked In

Resources
The Beginner's Guide to React
Epic React

Top comments (2)

Collapse
 
sreechandan profile image
Sree Chandan R

Im use vuejs and pretty much same thing is true for vue also. I used uuid to generate unique keys. Cool series. I wanted to be familier with react as much as I can incase im required to use it in some job or something.

Collapse
 
bipinrajbhar profile image
Bipin Rajbhar

Thanks 😊.

Right now I am working on new series called Basic Hooks.