JSX Fragments
In React.js, a JSX Fragment is a special syntax that lets you group multiple elements without adding extra nodes to the DOM.
Why We Need Fragments?
In React, a component must return a single parent element.
For example, this is invalid JSX:
function App() {
return (
Hello
Welcome to React!
);
}
Hereβs what happens:
Greeting is a React functional component.
It returns a piece of JSX, which React renders to the DOM.
The above will cause an error because JSX expressions must have one parent.
You could fix it by wrapping in a <div>, like this:
function App() {
return (
<div>
Hello
Welcome to React!
</div>
);
}
β¦but that adds an unnecessary
to the DOM, which can mess up styling or layouts.
JSX Fragments to the Rescue
A Fragment lets you group elements without creating extra DOM nodes.
import React from "react";
function App() {
return (
<React.Fragment>
Hello
Welcome to React!
</React.Fragment>
);
}
Short syntax:
You can also use the shorthand <>...</> (most common form):
function App() {
return (
<>
Hello
Welcome to React!
</>
);
}
Both versions are identical β the shorthand is just cleaner.