What's the deal with fragments in React?

Just a guy who loves to write code and watch anime.
Search for a command to run...

Just a guy who loves to write code and watch anime.
amazing read, always delivering quality articles
Qualities that make outstanding builders.

Bipedal vs quadrupedal: how many legs This is about the number of legs the creature walks on. Bipedal. Two legs. Humans, ostriches, T-rex, kangaroos, most fantasy humanoids. Quadrupedal. Four legs. Do

Intro You hear "lerp" and "smoothstep" everywhere in game dev. They sound like math jargon. They're not. Both are small tools that do the same job: smoothly move from one value to another. The problem

What is Kinematics Kinematics is the math field. It's the study of how things move without worrying about forces (which would be dynamics). FK and IK are the two branches: forward kinematics and inver

Intro Textures are usually the biggest cost in a 3D scene. Memory, bandwidth, and load time all get eaten by them. Resizing them is the obvious lever. There's more. This post is about the less obvious

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.
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.
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.