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 badges1 Answer
Reset to default 13You 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.
版权声明:本文标题:javascript - How can I render a Material UI grid using React without the unique key warning - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743874758a2554127.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论