Jacob Paris
← Back to all content

Add a Key to a React Fragment

When working with CSS Grid, nesting elements can break the layout.

js
const gridData = data.map(
({ id, firstName, lastName, team }) => {
return (
<>
<span>{firstName}</span>
<span>{lastName}</span>
<span>{team}</span>
</>
)
},
)

This function uses the <> fragment shorthand to return three <span> elements. With some CSS magic, it works great! But React will say that every element created in a loop needs a key.

The easy way to add the key is to add it to the parent, but since <key={id}> is an obvious syntax error, what can be done? Wrapping it in a <div key={id} solves the key issue but breaks the layout.

js
const gridData = data.map(
({ id, firstName, lastName, team }) => {
return (
<div key={id}>
<span>{firstName}</span>
<span>{lastName}</span>
<span>{team}</span>
</div>
)
},
)

One solution is to add keys directly to each child. Since keys need to be unique, you can tag each one with the field name it corresponds to. This is a perfectly valid solution

js
const gridData = data.map(
({ id, firstName, lastName, team }) => {
return (
<>
<span key={`${id}:firstName`}>
{player.firstName}
</span>
<span key={`${id}:lastName`}>
{player.lastName}
</span>
<span key={`${id}:team`}>
{player.team}
</span>
</>
)
},
)

But – as it turns out, the long-form React.Fragment has no problem accepting props, and we can just key on that instead.

js
const gridData = data.map(
({ id, firstName, lastName, team }) => {
return (
<React.Fragment key={id}>
<span>{firstName}</span>
<span>{lastName}</span>
<span>{team}</span>
</React.Fragment>
)
},
)
Professional headshot
Moulton
Moulton

Hey there! I'm a developer, designer, and digital nomad building cool things with Remix, and I'm also writing Moulton, the Remix Community Newsletter

About once per month, I send an email with:

  • New guides and tutorials
  • Upcoming talks, meetups, and events
  • Cool new libraries and packages
  • What's new in the latest versions of Remix

Stay up to date with everything in the Remix community by entering your email below.

Unsubscribe at any time.