liveBook · Manning

React.Fragment

As explained in Build a Frontend Web Framework (From Scratch)

A virtual DOM node that groups multiple children without adding a parent element to the rendered document.

Sometimes a component needs to return several children without adding a wrapper element to the page. A fragment groups those children in the virtual DOM. It is a container for virtual nodes, not an extra element in the rendered DOM. section 3.7 section 3.9

A small implementation gives fragments their own node type alongside text and element nodes. The hFragment() helper stores an array of children, removes null entries, and converts strings to text virtual nodes. section 3.4 section 3.7.1

export function hFragment(vNodes) {
  return {
    type: DOM_TYPES.FRAGMENT,
    children: mapTextNodes(withoutNulls(vNodes)),
  }
}

Notice that the returned object has children but no HTML tag name: the fragment groups nodes without describing a wrapper element. section 3.7.1

A component with several top-level children

A to-do application's App() function can return a fragment containing a heading, a form component, and a list component. They remain separate children rather than being placed inside an otherwise unnecessary wrapper. section 3.8.3

Mounting a fragment means mounting each child into the same parent element. The fragment's el reference points to that parent; nested fragments share the reference. For placement at a particular position, each child needs its own successive insertion index. section 4.1.3 section 8.1.4

Before reconciliation compares children, fragment children are extracted into the surrounding children array. This keeps the comparison close to the real DOM, where no fragment node appears. A browser DocumentFragment is a separate Document API facility; this implementation does not use one to insert virtual fragments. section 8.2.1 section 3.7

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Works through child mounting and reconciliation flattening rather than treating the fragment as a DOM element.
Examples
Uses a to-do application component that groups a heading, a form component, and a list component.
What it assumes
Introduces virtual-node types before fragment construction; assumes basic familiarity with JavaScript functions and DOM nodes.
What you can do after
Build it from scratch with hFragment(), then mount its children directly under a shared DOM parent.
How it connects
Connects virtual DOM trees and components to DOM mounting and reconciliation.

Also explained in

Compare how 2 books explain React.Fragment →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.