Lists and Keys

Bipin Rajbhar - Nov 2 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . .