Keys and arrays

Keys and arrays

Say that you’ve asked React to render an array of identical, uncontrolled inputs.

index.js
styles.css
import React from 'react'
import ReactDOM from 'react-dom'
import './styles.css'

let inputs = [
  <label><input type="checkbox" /> Bill</label>,
  <label><input type="checkbox" /> Jeff</label>,
  <label><input type="checkbox" /> Tim</label>,
  <label><input type="checkbox" /> Zuck</label>,
]
  
ReactDOM.render(
  inputs,
  document.getElementById('root')
)
Build In Progress

So far, so good — they render properly and you can type in them! But let’s think about this a little more.

When React encounters an array of elements with identical type and props, despite looking identical to React, it cannot know that they really are identical. For example, say that you check one of the inputs. Now you have four identical elements, but differing internal state.

At first, this isn’t a problem. After all, the state is internal. That’s the whole point.

But say that you then reorder the inputs. As all of the elements are identical, React won’t know that anything has changed, and is unable to reorder the corresponding DOM nodes. To demonstrate, let’s add some labels and a reverse button.

Notice what happens when you check an input and then click reverse.

index.js
styles.css
import React from 'react'
import ReactDOM from 'react-dom'

let fields = [
  <label><input type="checkbox" /> Bill</label>,
  <label><input type="checkbox" /> Jeff</label>,
  <label><input type="checkbox" /> Tim</label>,
  <label><input type="checkbox" /> Zuck</label>,
]

function App(props) {
  return (
    <div>
      <h2>RSVPs</h2>
      {props.fields}
      <button onClick={reverseAndRender}>Reverse</button>
    </div>
  )
}
  
function reverseAndRender() {
  ReactDOM.render(
    <App fields={fields.reverse().slice(0)} />,
    document.getElementById('root')
  )
}

reverseAndRender()
Build In Progress

Doh! The inputs are stuck. Luckily, even if React by itself can’t distinguish between array items, you can always give it a hand. That’s what the special key prop is for. By providing a key, you’re giving React a way to keep track of otherwise identical elements.

To see this in action, try adding unique key props to each of the fields above. Your keys can be strings or numbers — the only thing that matters is that they’re unique. Once you’ve added these, try reversing the list again — if the keys are in the right place, the inputs should be reversed too!

If you’re having any trouble with this, you can check the solution in the editor above — but do give it a shot first!

Progress to next section.