What Are React Fragments and When to Use Them
Grouping elements in React without adding an extra div.
When writing React components you'll run into this error sooner or later:
Adjacent JSX elements must be wrapped in an enclosing tag.
A component can only return one element. The quick fix is to wrap everything in
a div, which works, but it adds an extra node to the page. That can break a
flexbox or grid layout, and in places like tables and lists it makes the HTML
invalid. Fragments solve this.
A fragment lets you group elements without adding an extra node to the DOM.
What Is a React Fragment?
Wrap your elements in React.Fragment instead of a div:
import React from "react"function Greeting() {return (<React.Fragment><h1>Hello!</h1><p>Welcome back.</p></React.Fragment>)}
The rendered HTML is just the h1 and the p, with nothing around them.
The Short Syntax (the common way)
There's a shorter way to write a fragment, an empty tag:
function Greeting() {return (<><h1>Hello!</h1><p>Welcome back.</p></>)}
It does the same thing. (The short syntax needs Babel 7, which Create React App 2 and up already uses.)
When to Use Fragments
Table Rows
A component that returns table cells can't wrap them in a div, since a div
isn't allowed inside a tr:
function UserColumns({ user }) {return (<><td>{user.name}</td><td>{user.email}</td></>)}function UserRow({ user }) {return (<tr><UserColumns user={user} /></tr>)}
Showing a Group Conditionally
When you render conditionally and the condition covers more than one element, a fragment keeps them together:
function Nav({ isLoggedIn }) {return (<nav><a href="/">Home</a>{isLoggedIn && (<><a href="/account">Account</a><a href="/logout">Log out</a></>)}</nav>)}
The links stay direct children of the nav, so any styles on nav > a still
work.
Lists That Need a Key
The short syntax can't take props. When you map over a list and each item
returns more than one element, use React.Fragment with a key:
<dl>{terms.map((term) => (<React.Fragment key={term.id}><dt>{term.word}</dt><dd>{term.definition}</dd></React.Fragment>))}</dl>
There's more on keys in How to Render a List in React.
When to Use a div Instead
A fragment only accepts a key. If the wrapper needs a className, a style or
an event handler, that's a sign it should be a real element. Otherwise, use a
fragment and keep the extra divs out of your HTML.
Have some feedback on this post? .