Course contentsShow
← React
Lesson 181 of 2,3966. Component BasicsFree lesson

Returning Multiple Elements Requires a Wrapper

JSX expressions must have a single root element; use fragments or divs to wrap siblings.

Returning Multiple Elements Requires a Wrapper

What you'll learn: Why React components can't return multiple sibling elements without wrapping them, and how to fix it.

When you write a function component, you might be tempted to return multiple JSX elements side-by-side:

// ❌ This will throw an error!
function Greeting() {
  return (
    <h1>Hello!</h1>
    <p>Welcome back.</p>
  );
}

This breaks. React will immediately complain with a syntax error.

Why the Restriction Exists

Remember: JSX compiles to JavaScript function calls. When you write JSX, it becomes React.createElement(...) calls. A JavaScript function can only return one value, not two separate things sitting next to each other.

Think of it like trying to write:

return 5 10; // Not valid JavaScript!

You can't return two standalone values. Same with JSX—you can't return two sibling elements without a container.

The Solution: Wrap Siblings

You have two main options:

Option 1: Wrap in a <div>

function Greeting() {
  return (
    <div>
      <h1>Hello!</h1>
      <p>Welcome back.</p>
    </div>
  );
}

Option 2: Use a Fragment

function Greeting() {
  return (
    <>
      <h1>Hello!</h1>
      <p>Welcome back.</p>
    </>
  );
}

Fragments (<>...</>) let you group elements without adding extra DOM nodes—perfect when you don't want unnecessary wrapper divs cluttering your HTML.

Analogy

Think of packing groceries: you can't hand the cashier three loose apples. You need a bag (wrapper) to carry them together. Similarly, React needs a single "container" to return multiple elements.

Key Takeaway: JSX expressions must have exactly one root element—wrap multiple siblings in a <div> or <Fragment> to satisfy this rule.