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>
      )))}
    </>
  )
}

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>
      )))}
    </>
  )
}

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

2022 No rights reserved.
3D Heart