Imagine we want to create the following HTML structure:
<h1>Welcome to my blog!</h1>
<p>Don't forget to subscribe to the newsletter!</p>
We copy/paste this HTML into our React application, turning it into JSX. We wind up getting an error though:
The error message is telling us to use a โJSX fragmentโ, but how can we fix this issue? One option is to wrap both React elements in a div:
return (
<div>
<h1>Welcome to my blog!</h1>
<p>Don't forget to subscribe to the newsletter!</p>
</div>
);
So, this fixes the syntax error, but it's not really ideal. It pollutes the DOM with unnecessary elements. And it can even lead to accessibility and layout issues.
Fortunately, there's a better way. We can use fragments!
A fragment is a special React component that does not produce a DOM node. It looks like this:
If we inspect the output in our developer tools, we see that our two HTML elements, <h1>
and <p>
, sit directly inside the container element (<div id="root">
):
Fragments allow us to respect the rules of JavaScript without polluting the HTML. They're a great option!
React fragments can also be created using the following syntax:
return (
<>
<h1>Welcome to my blog!</h1>
<p>Don't forget to subscribe to the newsletter!</p>
</>
);
While this shorter way of writing it might look a bit weird at first, I actually find it pretty neat. The empty brackets (<>
) really help show that we're just grouping things together without adding any extra HTML.
๐. Similar posts
Write Cleaner and Faster Unit Tests with AssertJ as a Java Developer
12 May 2025
Understanding the useRef hook in React
28 Apr 2025
React Component Cleanup
12 Mar 2025