Fragments
React fragments group children without adding a wrapper DOM node. Use them when JSX needs a single root but the layout does not.
React Fragments
EXAMPLE
// ===== The problem =====
// JSX requires a single root element. But often you do not WANT an extra div.
// Wrapping every component in <div> bloats the DOM and breaks layout
// (CSS grid children, table rows, flex items all care about direct parents).
// ===== The long form =====
import { Fragment } from 'react';
function Row({ user }) {
return (
<Fragment>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.role}</td>
</Fragment>
);
}
// Render inside <tr>...<Row /></tr>. The <td>s become direct children of <tr>.
// ===== The short form (preferred for most uses) =====
function Row2({ user }) {
return (
<>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.role}</td>
</>
);
}
// ===== When you NEED the long form: keys in lists =====
// Short syntax <> cannot carry attributes. If you need a key, use <Fragment>:
function Glossary({ entries }) {
return (
<dl>
{entries.map((e) => (
<Fragment key={e.term}>
<dt>{e.term}</dt>
<dd>{e.definition}</dd>
</Fragment>
))}
</dl>
);
}
// ===== Common use cases =====
// 1. Table row cells (above)
// 2. List item siblings (dt + dd, label + input)
// 3. Returning multiple elements from a component
// 4. Conditional groups without extra divs
function FormRow({ label, name, value, onChange, error }) {
return (
<>
<label htmlFor={name}>{label}</label>
<input id={name} name={name} value={value} onChange={onChange} />
{error && <span role="alert">{error}</span>}
</>
);
}
// Parent owns the grid layout; child contributes 3 grid children, no wrapper.
// ===== Pitfalls =====
// - Trying to put a className or style on <>...</> -> use <div> or <Fragment key=...>
// - Using <Fragment> when a real semantic element (<section>, <ul>) is what the
// page needs; fragments hide structure from screen readers
// - Forgetting key on <Fragment> inside a map -> React warns
// - Wrapping a Fragment in a div 'just in case' -> defeats the point
Why it matters
Fragments are the smallest tool in JSX, and quietly one of the most useful. They keep markup semantic, keep the DOM clean, and stop you reaching for div-soup. Reach for <>...> by default; switch to
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…