How can I render a Material UI grid using React without the unique key warning

Viewed 1275

I am using React and Material UI for this project, and need to render a grid where the rows are from an array of data and the columns contain specific information like this:

<Grid container>
  {myData.map((record) => (
    <>
      <Grid item>{record.field1}</Grid>
      <Grid item>{record.field2}</Grid>
      <Grid item>{record.field3}</Grid>
    </>
  )}
</Grid>

This of course results in the React warning about items in the list not having unique keys.

The problem is that < key={index}> is not valid in React, and replacing <> with an actual tag like <div> for example messes up the grid; which expects grid items to be directly contained within the grid container.

Is there any way to work around this problem?

1 Answers

You can pass key's to an explicit <React.Fragment> component (which <> is short hand for).

React Docs - Keyed Fragments:

Fragments declared with the explicit <React.Fragment> syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:

function Glossary(props) {
  return (
    <dl>
      {props.items.map(item => (
        // Without the `key`, React will fire a key warning
        <React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}

key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.

Related