Skip to main content

Fragment

Check out the official React docs!

For more detailed information about React concepts and APIs, please refer to the official documentation for Fragment.


Fragment lets you group multiple elements without adding extra nodes to the DOM.

[<ReactComponent(true)>]
let FragmentDemo() =
React.Fragment [
// ... grouped elements
]

This is a heading inside a fragment

Fragments let you group multiple elements without adding extra nodes to the DOM.

Rightclick and inspect me to see I do not have a parent.

Show code
module Example.Fragment

open Feliz

[<ReactComponent(true)>]
let FragmentDemo () =
React.Fragment [
Html.h3 [ prop.text "This is a heading inside a fragment" ]
Html.p [
prop.text "Fragments let you group multiple elements without adding extra nodes to the DOM."
]
Html.button [ prop.text "Click me" ]
Html.p [
prop.text "Rightclick and inspect me to see I do not have a parent."
]
]

Fragment refs​

note

Requires React 19.3 or later.

A ref on a Fragment receives a FragmentInstance. It lets you work with the Fragment's first-level DOM children as a group, without adding a wrapper element: add event listeners, observe them with an IntersectionObserver or ResizeObserver, focus the first or last focusable element, measure them with getClientRects or scroll them into view.

let fieldsRef = React.useRef<FragmentInstance option> None

React.Fragment(fieldsRef, [
Html.input [ prop.placeholder "First name" ]
Html.input [ prop.placeholder "Last name" ]
])

// later, e.g. in an event handler
fieldsRef.current |> Option.iter (fun fields -> fields.focus ())
Show code
module Example.FragmentRef

open Feliz

[<ReactComponent(true)>]
let FragmentRef () =
let fieldsRef = React.useRef<FragmentInstance option> None

Html.div [
Html.button [
// Focuses the first focusable element inside the Fragment.
prop.onClick (fun _ -> fieldsRef.current |> Option.iter (fun fields -> fields.focus ()))
prop.text "Focus first field"
]
Html.div [
// No wrapper element: the inputs are direct children of this div.
React.Fragment(
fieldsRef,
[
Html.input [ prop.placeholder "First name" ]
Html.input [ prop.placeholder "Last name" ]
]
)
]
]

A callback ref can return a cleanup function, which React calls when the Fragment unmounts:

React.Fragment(
(fun fragment ->
fragment.observeUsing observer
fun () -> fragment.unobserveUsing observer),
children
)

Listeners and observers apply to the first-level DOM children only; focus and focusLast also search nested elements.