React Fragment is a common pattern in React for a component to return multiple elements. React Fragment let us group a list of children without adding extra nodes to the DOM. This avoids the common pitfall in React when a component needs to return multiple elements.
Consider the following practical example. You may often find yourself writing extra <div>
tags in your components to satisfy React's single root element requirement for each component's render method:
class Example extends React.Component {
render() {
return (
<div>
<ChildA />
<ChildB />
<ChildC />
</div>
);
}
}
In the above example, the extra <div>
tag isn't really needed, and might even interfere with CSS styles. This is a perfect use-case for a React Fragment. Fragments let you group a list of children without adding extra nodes to the DOM:
class Example extends React.Component {
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
}
Here we are using the shorthand syntax for declaring fragments. It looks a lot like empty tags which are essentially syntactic sugar for <React.Fragment>...</React.Fragment>
. This new feature in React gives us the power to return multiple sibling elements from your components without the need of a wrapping div.
While fragments are a powerful solution to the problem of returning multiple elements from a component, they are a tool to be used judiciously. Often, a component does need to return a structured HTML element, like a <div>
or <span>
, that can be styled or positioned. Fragments are most useful in cases where adding an extra node to the DOM would disrupt this structure or style. If the parent node is already serving an important role, then fragments can be a handy way to include multiple child nodes without altering the DOM tree.
React Fragments make the code more readable, clean, and improves performance by reducing the number of nodes in a DOM tree. This new feature released by the React team is really helpful for developers to write cleaner and efficient code.