4

I have a React component that needs to break down this.props.children in to chunks, and render each chunk in a wrapping element (i.e. a grid of child components).

I'm following airbnb's React linting, which includes a rule that prevents me using the array index as a key:

react/no-array-index-key : Do not use Array index in keys

This rule specifies I need a unique key for each set of children that is not the array index - but I have no other identifier that I can use.

Is it ok to ignore this rule in such circumstances?

Alasdair McLeay
  • 2,572
  • 4
  • 27
  • 50
  • Here's an explanation that goes into more detail about when it is ok, and when not, to ignore this linting rule: https://stackoverflow.com/a/43892905/12484 – Jon Schneider Jun 18 '18 at 20:56

1 Answers1

4

Array indices make bad keys, since indices do not uniquely identify a specific array element as such, but rather any element at a specific position in the array. If this shifts, the identification breaks.

Do your items that make up each chunk have an id? Then you could generate a key e.g. by hashing a combination of the ids to uniquely identify each chunk.


If that is not an option, use the array index and ignore the message. You should try to avoid this however:

When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

We don't recommend using indexes for keys if the items can reorder, as that would be slow.

Source

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94