ReactEasy

What is a Fragment?

A Fragment groups multiple elements without adding an extra node to the DOM. Write <>...</> for the short form, or <Fragment key={id}>...</Fragment> when you need a key in a list. Since React 19.3, <Fragment ref={...}> also gives you a Fragment ref to act on all its child DOM nodes.

Why use it

  • A component must return a single root; Fragments satisfy this without a wrapper <div>.
  • Wrapper divs can break layouts (CSS Grid or Flex children) and HTML validity (<tr> must contain <td>, not <div>).
  • Fewer DOM nodes.

Short vs long syntax

  • <>...</>: cannot take attributes.
  • <Fragment>: accepts key (for lists) and, from React 19.3, ref.

Fragment refs (React 19.3, stable)

<Fragment ref={fragmentRef}> gives a FragmentInstance that represents the Fragment's first-level DOM children. Its methods include addEventListener, removeEventListener, dispatchEvent, focus, focusLast, blur, observeUsing (for IntersectionObserver or ResizeObserver), getClientRects and scrollIntoView. It is useful for focus management or observing visibility of a group of elements without a wrapper.

State behavior

Switching between <> with children and children without a wrapper at the same position keeps state only when the tree shape is the same; adding or removing a wrapper changes the structure.

Code example

tsx
1import { Fragment, useEffect, useRef } from "react";
2
3type Row = { id: string; term: string; desc: string };
4
5// Fragments with keys in a list (a <div> would be invalid inside <dl>)
6export function Glossary({ rows }: { rows: Row[] }) {
7 return (
8 <dl>
9 {rows.map((r) => (
10 <Fragment key={r.id}>
11 <dt>{r.term}</dt>
12 <dd>{r.desc}</dd>
13 </Fragment>
14 ))}
15 </dl>
16 );
17}
18
19// React 19.3: Fragment ref, observe a group of nodes without a wrapper element
20export function TrackVisibility({ children }: { children: React.ReactNode }) {
21 const ref = useRef<any>(null);
22 useEffect(() => {
23 const io = new IntersectionObserver((entries) => console.log("visible:", entries.some((e) => e.isIntersecting)));
24 ref.current?.observeUsing(io);
25 return () => ref.current?.unobserveUsing(io);
26 }, []);
27 return <Fragment ref={ref}>{children}</Fragment>;
28}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app