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
Stop Installing Node Modules on Your Docker Host - Install Them in the Container Instead
14 Jan 2025
An Easy to Understand React Component Introduction for Beginners
14 Jan 2025
What is JSX? A Beginner’s Guide to JavaScript XML in React
12 Jan 2025