admin管理员组

文章数量:1353127

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?

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?

Share Improve this question asked Dec 16, 2020 at 22:06 bikeman868bikeman868 2,64730 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

You can pass key's to an explicit <React.Fragment> ponent (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.

本文标签: javascriptHow can I render a Material UI grid using React without the unique key warningStack Overflow