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
How to Effectively Use the React useId Hook in Your Apps
16 Feb 2025
The Simple Method for Lifting State Up in React Effectively
16 Feb 2025
How to Master Dynamic Key Generation in React for Your Apps
12 Feb 2025