DEV Community

Paul Bennett
Paul Bennett

Posted on

3 2

Rending arrays in React properly.

I guess you have used .map quite a bit and understand how it works well. We can use .map in React too. It helps us render arrays to the page. For me I have never really used a key within a map function for vanilla JS, for React though it's pretty essential, let's see why.

Let's say we have the following component. That renders an array of fruit.

const allItems = [
  {id: 'apple', value: '๐ŸŽ apple'},
  {id: 'orange', value: '๐ŸŠ orange'},
  {id: 'grape', value: '๐Ÿ‡ grape'},
  {id: 'pear', value: '๐Ÿ pear'},
]

function Keys() {
  return (
    <>
      {allItems.map((item => (
        <li>
          <label>{item.value}</label>
        </li>
      )))}
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

With the above example, React will throw an warning:

Warning: Each child in a list should have a unique "key" prop.

Now your .map function will render the contents of the array without any issue, I mean it is just a "warning" however without a key prop added it can all go wrong.

We need to add a key prop to the child of our .map function to allow React to know the element's position. You can test this going to the below link and clicking on the elements.

https://react-fundamentals.netlify.app/isolated/final/07.extra-1.js

See how the first two examples differ from the last one. Youโ€™ll notice that using the array index as a key is no different from Reactโ€™s default behaviour. Using an index is incorrect, as you can see from the focus states here, the focus will always stay on that index. Instead of moving with the element, like it does when using a key.

As the key must be unique, we should code it up as such:

const allItems = [
  {id: 'apple', value: '๐ŸŽ apple'},
  {id: 'orange', value: '๐ŸŠ orange'},
  {id: 'grape', value: '๐Ÿ‡ grape'},
  {id: 'pear', value: '๐Ÿ pear'},
]

function Keys() {
  return (
    <>
      {allItems.map((item => (
        <li key={item.id}>
          <label>{item.value}</label>
        </li>
      )))}
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Thanks to Kent C Dodds for explaining this like a true hero.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs