Fragments & Returning Multiple Elements

Reviewed & published by Brayan K

A fragment is a wrapper that lets a component return several sibling elements as one without adding an extra DOM node. You write it as the shorthand <>...</> or the full <React.Fragment>, which keeps your HTML flat and avoids unnecessary wrapper-div clutter.

Part of the free React course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

What You'll Learn

1️⃣ Why One Root — and the Fragment Fix

A component's return is a single expression, so it must produce one element. Returning two siblings is invalid. A fragment groups them into one returned element while rendering nothing extra to the DOM.

// ❌ Two siblings — "Adjacent JSX elements must be wrapped"
function Bad() {
  return (
    <h1>Title</h1>
    <p>Body</p>
  );
}

// ✅ One fragment groups them, no extra <div>
function Good() {
  return (
    <>
      <h1>Title</h1>
      <p>Body</p>
    </>
  );
}
// A return is ONE expression -> ONE element.
// Returning two siblings is like returning two values:
function twoValues() {
  // return 1, 2;  // ❌ only the last is kept
  return [1, 2];    // ✅ group them into ONE thing
}

console.log(twoValues());          // [1, 2]
console.log(twoValues().length);   // 2
// A fragment groups JSX siblings the same way — into one returned element.

2️⃣ Shorthand vs React.Fragment & Wrapper Soup

The shorthand <>...</> is the everyday choice, but it cannot take props. When you map a list and each item needs two elements under one key, use the full form <React.Fragment key={id}>. Reaching for a real div every time instead leads to wrapper-div soup — stacks of meaningless nodes that bloat the DOM and break flex/grid layouts.

function Glossary({ items }) {
  return (
    <dl>
      {items.map(item => (
        <React.Fragment key={item.id}>    
          <dt>{item.term}</dt>
          <dd>{item.def}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}
// "Wrapper div soup": extra <div>s pile up and can break layout.
// Count how many wrappers a nested structure adds.
function wrappers(depth) {
  let html = "content";
  for (let i = 0; i < depth; i++) {
    html = "<div>" + html + "</div>";   // each level = one extra node
  }
  return html;
}

console.log(wrappers(0));   // content        (fragment: 0 extra nodes)
console.log(wrappers(2));   // <div><div>content</div></div>

Your turn — produce a keyed label list:

// 🎯 YOUR TURN — fill in each ___ then press "Try it Yourself".
// A keyed fragment in a list groups two elements per item under ONE key.
// 1) Map each item to a label that includes its key (the id).
// 2) Join the labels with ", ".

const items = [
  { id: "a", term: "JSX", def: "syntax" },
  { id: "b", term: "Props", def: "inputs" },
];

const labels = items.map(item => item.___ + ":" + item.term);  // 👉 id
console.log(labels.___(", "));                                  // 👉 join

// ✅ Expected output:
//    a:JSX, b:Props

3️⃣ Fragment or Div? Make the Call

Ask one question: does the wrapper need to do anything — carry a class, a style, an event handler, or act as a layout box? If yes, use a div. If the wrapper exists only to satisfy the one-root rule, use a fragment so the DOM stays clean and parent layouts (like a flex row) treat your children as direct siblings.

// Needs styling/layout  -> real element
function Box({ children }) { return <div className="box">{children}</div>; }

// Purely structural      -> fragment (children become direct siblings)
function Columns() {
  return (
    <>
      <Cell />
      <Cell />
    </>
  );
}

🧩 Reorder Challenge

These lines return two siblings using the fragment shorthand. Put them in the right order:

A.   <h1>Welcome</h1>
B.   return (
C.   </>
D.   <>
E.   <p>Glad you are here</p>

Common Errors (and the fix)

📋 Quick Reference

NeedUse
Group siblings, no node<>...</>
Keyed group in a list<React.Fragment key={id}>
Styled / layout box<div className="...">
Avoidwrapper-div soup

🧠 Quick Recall

1. Does a fragment add a DOM node?

No. It renders its children directly with zero extra elements.

2. When must you use <React.Fragment> over <></>?

When you need to pass a prop such as key; the shorthand cannot take props.

3. Fragment or div for a styled card?

A div — you need a real element to attach the class and box styling.

Mini-Challenge: Flatten Without Wrappers

Each pair should contribute two flat entries — just like a keyed fragment emits two siblings per item. Run it and check your output.

// 🎯 MINI-CHALLENGE: flatten without extra wrappers
//
// A fragment lets each item contribute MULTIPLE elements to one flat list.
// 1. For each pair, produce TWO entries: the term, then the definition.
// 2. flatMap them into a single flat array.
// 3. console.log the flat list joined by " | ".
//
// ✅ Expected output:
//    JSX | a syntax | Props | inputs

const pairs = [
  { term: "JSX", def: "a syntax" },
  { term: "Props", def: "inputs" },
];

// your code here

🎉 Lesson Complete

Practice quiz

Why must a React component's return produce a single root element?

  • Because React only renders the first element returned
  • Because the browser DOM only allows one element per page
  • Because the return is one JavaScript expression that evaluates to one element
  • Because JSX cannot contain more than one tag

Answer: Because the return is one JavaScript expression that evaluates to one element. A return is a single expression, so it must evaluate to one element. A fragment groups siblings into that one element.

What does a fragment add to the rendered DOM?

  • Nothing — it renders its children with no extra node
  • A <div> wrapper
  • A <span> wrapper
  • A comment node

Answer: Nothing — it renders its children with no extra node. Fragments render their children directly and add zero extra DOM nodes, keeping the HTML flat.

Which is the shorthand syntax for a fragment?

  • <Fragment>...</Fragment>
  • <React.Fragment>...</React.Fragment>
  • <div>...</div>
  • <>...</>

Answer: <>...</>. <>...</> is the fragment shorthand. It groups siblings without a wrapper node.

What is the key limitation of the shorthand <>...</> fragment?

  • It cannot contain text
  • It cannot take any props, including key
  • It can only hold two children
  • It adds a DOM node

Answer: It cannot take any props, including key. The shorthand cannot accept props. When you need a key, use the full <React.Fragment key={...}> form.

When mapping a list where each item needs two elements under one key, which should you use?

  • <React.Fragment key={id}>...</React.Fragment>
  • <>...</> with a key prop
  • A <div key={id}> wrapper always
  • No key is needed for fragments

Answer: <React.Fragment key={id}>...</React.Fragment>. Only the full <React.Fragment> form accepts a key, so it is required for keyed groups in a list.

What error appears if you return two sibling elements with no wrapper?

  • "Too many children"
  • "Missing key prop"
  • "Adjacent JSX elements must be wrapped in an enclosing tag"
  • "Cannot read property of undefined"

Answer: "Adjacent JSX elements must be wrapped in an enclosing tag". Two siblings without a parent are invalid; React tells you to wrap them, which a fragment does without a node.

When should you reach for a real <div> instead of a fragment?

  • Whenever you return more than one element
  • When the wrapper needs a class, style, event handler, or to act as a layout box
  • Never — fragments always work
  • Only inside lists

Answer: When the wrapper needs a class, style, event handler, or to act as a layout box. Use a div when the wrapper must actually do something; use a fragment when it would be purely structural.

How can an accidental wrapper <div> break a flexbox or grid layout?

  • It changes the font size
  • It removes the children from the DOM
  • It disables the layout entirely
  • It makes the children no longer direct children of the flex/grid container

Answer: It makes the children no longer direct children of the flex/grid container. Flex/grid styles only apply to direct children; an extra div nests them one level deeper, breaking the layout.

Are <>...</> and <React.Fragment> functionally the same when no props are needed?

  • No, the shorthand renders a span
  • Yes — they mean the same thing; the long form just also accepts props
  • No, the long form adds a DOM node
  • Yes, but only in React 19

Answer: Yes — they mean the same thing; the long form just also accepts props. They are equivalent for grouping; the full form additionally allows passing props such as key.

What is "wrapper-div soup"?

  • A CSS framework
  • A way to optimize rendering
  • Stacks of meaningless wrapper divs that bloat the DOM and can break layouts
  • A React 19 feature

Answer: Stacks of meaningless wrapper divs that bloat the DOM and can break layouts. Reaching for a div whenever you need to group siblings piles up meaningless nodes; fragments avoid it.

Continue this course

Frequently asked questions

Why must a component return one element?

Because the return is a single JavaScript expression that compiles to one element object. Two siblings would be two values. A fragment groups them into one without adding a DOM node.

What is the difference between <></> and <React.Fragment>?

They mean the same thing, but the shorthand <></> cannot take props. When you need a key (for example inside a list), use the long form <React.Fragment key={...}>.

Does a fragment add an element to the page?

No. Fragments render their children directly with no extra wrapper, which keeps your HTML flat and avoids breaking CSS layouts like flexbox or grid.

When should I still use a real div?

Whenever you actually need a styled box, a class, an event handler, or a layout container. Use a fragment only when the wrapper would be purely structural and unwanted.