Add a Key to a React Fragment
When working with CSS Grid, nesting elements can break the layout.
1const gridData = data.map(2 ({ id, firstName, lastName, team }) => {3 return (4 <>5 <span>{firstName}</span>6 <span>{lastName}</span>7 <span>{team}</span>8 </>9 )10 },11)12
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.
1const gridData = data.map(2 ({ id, firstName, lastName, team }) => {3 return (4 <div key={id}>5 <span>{firstName}</span>6 <span>{lastName}</span>7 <span>{team}</span>8 </div>9 )10 },11)12
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> ) },)