Add a Key to a React Fragment
When working with CSS Grid, nesting elements can break the layout.
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.
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
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.
const gridData = data.map( ({ id, firstName, lastName, team }) => { return ( <React.Fragment key={id}> <span>{firstName}</span> <span>{lastName}</span> <span>{team}</span> </React.Fragment> ) },)