Trying to use multiple root elements in JSX without a wrapper

Loading

Handling Multiple Root Elements in JSX

When you need to return multiple elements in JSX without a wrapping DOM element, you have several proper solutions:

1. React Fragments (Recommended)

The most modern and clean approach:

function Component() {
  return (
    <>
      <h1>Title</h1>
      <p>Description</p>
      <button>Click me</button>
    </>
  );
}

Or the explicit version:

function Component() {
  return (
    <React.Fragment>
      <h1>Title</h1>
      <p>Description</p>
      <button>Click me</button>
    </React.Fragment>
  );
}

2. Array Return (For Dynamic Lists)

function Items() {
  return [
    <li key="1">Item 1</li>,
    <li key="2">Item 2</li>,
    <li key="3">Item 3</li>
  ];
}

Note: Keys are required when returning arrays.

3. Higher-Order Component Wrapper

For reusable fragment behavior:

const FragmentWrapper = ({ children }) => <>{children}</>;

function Component() {
  return (
    <FragmentWrapper>
      <h1>Title</h1>
      <p>Description</p>
    </FragmentWrapper>
  );
}

Why Fragments Over Div Wrappers?

  1. No extra DOM nodes – Fragments don’t render to the DOM
  2. Better for CSS – No unintended layout changes
  3. Semantic correctness – When wrapper elements would violate HTML structure rules
  4. Performance – Slightly faster rendering

Common Use Cases

1. Table Structures

function TableData() {
  return (
    <table>
      <tbody>
        <tr>
          <Columns /> {/* Returns multiple <td> without wrapper */}
        </tr>
      </tbody>
    </table>
  );
}

function Columns() {
  return (
    <>
      <td>Data 1</td>
      <td>Data 2</td>
    </>
  );
}

2. Conditional Groups

function Notification() {
  return (
    <>
      {isError && <ErrorIcon />}
      <Message />
      {!isError && <DismissButton />}
    </>
  );
}

Migration from Older Patterns

If you previously used:

<div className="hidden-wrapper">
  {/* children */}
</div>

Replace with:

<>
  {/* children */}
</>

And remove any wrapper-specific CSS.

Key Considerations

  1. Fragments can have keys when used in arrays:
   {items.map(item => (
     <React.Fragment key={item.id}>
       <h2>{item.title}</h2>
       <p>{item.desc}</p>
     </React.Fragment>
   ))}
  1. Fragments don’t support props (except key)
  2. Some CSS-in-JS libraries may need updates to support fragment contexts

This pattern works in all modern React versions (16.2+) and is the recommended solution for returning multiple elements.

Leave a Reply

Your email address will not be published. Required fields are marked *