Why sibling elements require a wrapper
In React, a component must return a single element. If you try to return multiple sibling elements without wrapping them, you'll encounter an error.
Let's dive into why this happens and how to fix it using React Fragments.
Problematic code
function App() {
return (
<h1>Hello</h1>
<h2>World</h2>
);
}
This code will throw an error because React expects a single root element to be returned from a component. When transpiled, the code looks like this:
return React.createElement("h1", null, "Hello");
return React.createElement("h2", null, "World");
The issue is that we're attempting to return two separate elements. The function will exit after the first return statement, and the second line will never be executed.
Fragments to the rescue
To solve this problem, we can use React.Fragment
to wrap the multiple elements and return them as a single element:
function App() {
return (
<React.Fragment>
<h1>Hello</h1>
<h2>World</h2>
</React.Fragment>
);
}
When transpiled, it becomes:
return React.createElement(
React.Fragment,
null,
React.createElement("h1", null, "Hello"),
React.createElement("h2", null, "World")
);
Alternatively, you can use the shorthand syntax <>
and </>
:
function App() {
return (
<>
<h1>Hello</h1>
<h2>World</h2>
</>
);
}
React Fragments allow you to group multiple elements without adding an extra DOM node, keeping your component's structure clean and efficient.