Advertisement
Intermediate React, Components & JSX

Why does JSX require every element to have exactly one parent element or a Fragment?

Short answer

Under the hood, JSX is converted into a single function call that returns one value, so it cannot return two separate elements sitting side by side.

Save React mock interview
Advertisement
AModel answer
Under the hood, JSX is converted into a single function call that returns one value, so it cannot return two separate elements sitting side by side. Wrapping everything in one parent div, or using a Fragment when you do not want an extra element in the final HTML, solves this requirement.
// This causes an error, two elements with no single parent
// return (<h1>Title</h1><p>Text</p>);

// Correct, wrapped in a Fragment
return (
  <>
    <h1>Title</h1>
    <p>Text</p>
  </>
);
Real-world example
A component needs to return a heading and a paragraph without adding an extra wrapping div that might mess up the page's CSS layout, so the team uses a Fragment instead.
Likely follow-ups
  • What is the shorthand syntax for a Fragment, and when can you not use it?
  • Why might using an extra div instead of a Fragment sometimes break a page's styling?
Related topics