Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 800
bikeman868 Avatar asked Oct 28 '25 10:10

bikeman868


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.

like image 140
JBallin Avatar answered Oct 30 '25 00:10

JBallin