Search code examples
reactjs

How to define key when rendering multiple items without root in React?


Given the following code:

someArray.map(item => 
    <>
        <p>{item.Name}</p>
        <p>{item.Value}</p>
    </>

How and where should I define the key property, so that React doesn't complain?

A plot twist: I can not replace <></> with e.g. <span> or <div>, because it will break the layout.


Solution

  • to accept keys, you have to use the imported <Fragment> instead of <> as <> cannot accept keys.

    i.e.

    import { Fragment } from 'react';
    
    ...
    
    <Fragment key={yourKey}>...</Fragment>