Advertisement
Intermediate React, Portals & Fragments

How would you use a keyed Fragment when rendering a list of grouped elements?

Short answer

When mapping over a list and returning more than one element per item, you cannot use the short Fragment syntax if you also need to add a key, since the shorthand does not accept any props at all. Instead you write out React.Fragment fully and add the key directly to it.

Save React mock interview
Advertisement
AModel answer
When mapping over a list and returning more than one element per item, you cannot use the short Fragment syntax if you also need to add a key, since the shorthand does not accept any props at all. Instead you write out React.Fragment fully and add the key directly to it.
function DefinitionList({ terms }) {
  return (
    <dl>
      {terms.map((term) => (
        <React.Fragment key={term.id}>
          <dt>{term.name}</dt>
          <dd>{term.definition}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}
Real-world example
A glossary page correctly groups each term and its definition together using a keyed Fragment, avoiding both an unnecessary wrapping div and the React warning about a missing key on list items.
Likely follow-ups
  • Why does React require a key here even though a Fragment itself never renders any actual HTML element?
  • What warning does React show if you forget the key on these Fragments?
Related topics