Skip to main content

What does `<React.Fragment>` do?

React.Fragment is a special wrapper component in React that lets you group multiple elements without adding an extra node to the DOM.


The problem React.Fragment solves

In React, every component must return a single root element:

javascript
function App() { return ( <h1>Hello</h1> <p>How are you?</p> ); }

Error:

"Adjacent JSX elements must be wrapped in an enclosing tag."

To fix this, you can wrap the elements in a <div>, but that creates an extra HTML element:

javascript
function App() { return ( <div> <h1>Hello</h1> <p>How are you?</p> </div> ); }

The DOM will contain:

javascript
<div> <h1>Hello</h1> <p>How are you?</p> </div>

Sometimes that <div> is not needed at all (for example, inside a table, a list, or a grid).


The solution: <React.Fragment>

javascript
function App() { return ( <React.Fragment> <h1>Hello</h1> <p>How are you?</p> </React.Fragment> ); }

Now React groups the elements logically, but does not add a wrapper to the DOM.

As a result, the DOM looks like this:

javascript
<h1>Hello</h1> <p>How are you?</p>

Short syntax: <>...</>

The same thing, just shorter:

javascript
function App() { return ( <> <h1>Hello</h1> <p>How are you?</p> </> ); }

This is syntactic sugar for <React.Fragment>.


When it is especially useful

  1. In tables and lists:
javascript
function TableRow() { return ( <> <td>Name</td> <td>Age</td> </> ); }

Without Fragment you would have to use an extra <tr> or <div>, which breaks the table. 2. When returning multiple elements from map:

javascript
const items = ["apple", "banana", "orange"]; return items.map((fruit, i) => ( <React.Fragment key={i}> <h3>{fruit}</h3> <hr /> </React.Fragment> ));

Here key can only be set with React.Fragment, since the short syntax <>...</> does not support keys.


Summary

What it doesExplanation
Groups multiple JSX elementsWithout adding an extra element to the DOM
Lets you avoid unnecessary <div>Especially in tables and lists
Can have a keyOnly the full <React.Fragment key={...}> form
Does not render in the DOMIt is an "invisible" wrapper

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.