Recipe Book0.6.0

4.4React reference

System toggle

Reference for <Recipe.SystemToggle> and <Recipe.SystemOption>, a radio group that switches a recipe between metric and US units.

§ 4.414 min readView as Markdown

Two parts let readers switch a recipe between metric and US units. <Recipe.SystemToggle> renders a radio group, and <Recipe.SystemOption> renders one option in it. The toggle shows and sets the measurement system of the nearest <Recipe.Root>, so it must be inside one.

  • 1 ½ cups all-purpose flour
  • 2 tbsp sugar
  • 2 tsp baking powder
  • 1 ¼ cups buttermilk
  • 2 eggs
  • 3 tbsp butter, melted
  • maple syrup, to serve

SystemToggle

TSX
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function Units({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.SystemToggle className="units" />
    </Recipe.Root>
  )
}

For the sample recipe, which is written in US units, US starts checked, and Units renders this HTML, indented here for reading:

HTML
<div class="units" aria-label="Measurement system" role="radiogroup" data-recipe-system-toggle="">
  <button autoComplete="off" type="button" role="radio" aria-checked="false" tabindex="-1" data-recipe-system-option="" data-state="unchecked">Metric</button>
  <button autoComplete="off" type="button" role="radio" aria-checked="true" tabindex="0" data-recipe-system-option="" data-state="checked">US</button>
</div>

A click on Metric checks it and switches the Root to metric, so a <Recipe.Ingredients> in the same Root shows metric quantities. On React 18, checking an option while a Suspense boundary inside the Root hasn’t hydrated yet, such as one waiting for a lazy component’s code, makes React report error #421, throw away that boundary’s server HTML, and show its fallback until the code loads. The file needs no 'use client', because the parts are already Client Components.

To style the toggle, pass a className.

Name Type Description
asChild boolean | undefined Renders the group as its one element child instead of a <div>. See Render your own elements. Defaults to false.
children ReactNode | undefined The options. Defaults to a <Recipe.SystemOption> for 'metric', then one for 'us'.
aria-label string | undefined The group’s accessible name. Defaults to labels.system. An aria-labelledby whose element has text outranks it. See Name controls to match your layout.

Any other <div> prop, such as className or aria-labelledby, passes to the <div>, except role, aria-disabled, and the data attributes, which the group sets itself. An asChild child’s own role, aria-disabled, or data attribute wins over the group’s. The group renders its own content, so it doesn’t take dangerouslySetInnerHTML. A ref reaches the <div>.

Recipes that can’t convert

The toggle is enabled when the Root’s canConvert is true: an ingredient’s quantity, or any equivalent of a quantity in a count unit, such as the size of a can, has a unit that belongs to only one system, or a <Recipe.StepText>, such as the one in each default <Recipe.Step>, or a <Recipe.ConvertedStepText> in the Root shows a temperature, or a <Recipe.ConvertedStepText> shows a quantity that one of the systems would convert. Otherwise it still renders, but disabled. Each option is disabled, so clicking one doesn’t select it and the arrow keys do nothing. For a recipe whose only ingredient is 2 slices of bread, <Recipe.SystemToggle /> renders:

HTML
<div aria-label="Measurement system" role="radiogroup" aria-disabled="true" data-recipe-system-toggle="" data-disabled="">
  <button autoComplete="off" type="button" role="radio" aria-checked="true" tabindex="-1" disabled="" data-recipe-system-option="" data-state="checked" data-disabled="">Metric</button>
  <button autoComplete="off" type="button" role="radio" aria-checked="false" tabindex="-1" disabled="" data-recipe-system-option="" data-state="unchecked" data-disabled="">US</button>
</div>

A <Recipe.StepText> or <Recipe.ConvertedStepText> counts once it mounts in the browser, and stops counting when it unmounts, or while React 19.2’s <Activity mode="hidden"> hides it. So when only the steps can convert, as for the bread recipe with the step “Bake at 180°C.”, the toggle renders disabled on the server, as above, and enables once React hydrates the page. A view that shows one step at a time enables the toggle only while the step it shows has a temperature, or its <Recipe.ConvertedStepText> shows a quantity that one of the systems would convert, so the toggle agrees with what the page converts.

To hide the toggle instead, render it only when canConvert from useRecipe() is true:

TSX
'use client'

import * as Recipe from '@recipe-book/react'

export function Units() {
  const { canConvert } = Recipe.useRecipe()
  return canConvert ? <Recipe.SystemToggle /> : null
}

When only the steps can convert, Units renders nothing on the server, and the toggle appears after hydration.

SystemOption

TSX
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function Units({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.SystemToggle>
        <Recipe.SystemOption value="us">Cups and spoons</Recipe.SystemOption>
        <Recipe.SystemOption value="metric">
          Grams and milliliters
        </Recipe.SystemOption>
      </Recipe.SystemToggle>
    </Recipe.Root>
  )
}

For the sample recipe, Units renders:

HTML
<div aria-label="Measurement system" role="radiogroup" data-recipe-system-toggle="">
  <button autoComplete="off" type="button" role="radio" aria-checked="true" tabindex="0" data-recipe-system-option="" data-state="checked">Cups and spoons</button>
  <button autoComplete="off" type="button" role="radio" aria-checked="false" tabindex="-1" data-recipe-system-option="" data-state="unchecked">Grams and milliliters</button>
</div>

<Recipe.SystemOption> renders a <button> with role="radio". It’s checked, with aria-checked="true", when its value is the Root’s system, and a click sets the Root’s system to value. Compose the options yourself to change their order or their text.

Name Type Description
value System The system the option selects: 'metric' or 'us'.
asChild boolean | undefined Renders the option as its one element child instead of a <button>. See Render your own elements. Defaults to false.
autoComplete string | undefined The button’s autocomplete attribute. Defaults to 'off', so when going back reloads the page, Firefox doesn’t re-enable an option that the server rendered disabled and the page enabled later. null (from JavaScript, or without strictNullChecks) leaves the attribute out.
children ReactNode | undefined The option’s text. Defaults to labels.metric or labels.us, by value.
disabled boolean | undefined Disables the option, so clicking it doesn’t select it and the arrow keys skip it. It stays disabled while the toggle is disabled, even with disabled={false}. Defaults to false.
type 'submit' | 'reset' | 'button' | undefined The button’s type. Defaults to 'button', so the option doesn’t submit a form.

Any other <button> prop passes to the <button>, except role, aria-checked, tabIndex, and the data attributes, which the option sets itself. An asChild child’s own role, aria-checked, or data attribute wins over the option’s. The option renders its own content, so it doesn’t take dangerouslySetInnerHTML. A ref reaches the <button>. Your onClick and onKeyDown, and an asChild child’s, run before the option’s own handling. Call event.preventDefault() in them to stop a click from setting the system, or an arrow key from moving.

Keyboard

The options share one tab stop, as in any radio group:

  • Tab moves focus to the checked option. When it’s disabled, focus goes to the first enabled option. With two options for one system, an option that mounts or is re-enabled later counts as the last option for the tab stop, wherever it is in the group. Until an option whose value is the current measurement system hydrates, every enabled checked option is a tab stop, so if every checked option is disabled, the group has none. A group with no option whose value is the current measurement system has no tab stop, before or after hydration, so Tab skips it.
  • Right Arrow and Down Arrow move focus to the next option and check it. From the last option, they wrap to the first.
  • Left Arrow and Up Arrow move focus to the previous option and check it. From the first option, they wrap to the last.
  • Space and Enter check the focused option, as a click does.
  • Home and End don’t move focus or check an option, so the browser handles them as usual, such as by scrolling the page.

The arrow keys skip disabled options and any option that can’t take focus: one that display: none hides, such as one inside an element with hidden or inside React 19.2’s <Activity mode="hidden">, one under visibility: hidden or inert, or one in a closed <details>. They do nothing while Alt, Ctrl, Meta, or Shift is held. They check an option by clicking it, so its onClick runs, and calling event.preventDefault() there leaves the option focused but not checked. Left Arrow and Right Arrow follow the toggle’s computed direction, so they swap in a right-to-left layout, as under dir="rtl" or CSS direction: rtl. An option’s own dir, such as dir="auto" on a label in Hebrew, doesn’t change them.

Tab also skips the toggle while the option for the current measurement system is hidden or isn’t rendered, because the tab stop doesn’t move to another option. That includes display: none, such as from hidden on the option or on an element around it, from a stylesheet, or from React 19.2’s <Activity mode="hidden">, as well as visibility: hidden, inert, and a closed <details>. To keep the toggle in the tab order, hide only an option for a system the Root won’t switch to: before you hide the option that’s checked, call setSystem with a system whose option shows.

An onKeyDownCapture on <Recipe.SystemToggle> passes to the group, like its other props, so it runs before the options’ own handling. Calling event.preventDefault() in it for an arrow key keeps focus and the system as they are. An onKeyDown there runs only after focus has moved to the next option and that option’s click has run, so it’s too late to stop either.

Controlled and uncontrolled

The toggle follows the Root’s controlled or uncontrolled state. A controlled system can keep several recipes in one system:

TSX
'use client'

import type { ParsedRecipe, System } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useState } from 'react'

export function MealPlan({ recipes }: { recipes: ParsedRecipe[] }) {
  const [system, setSystem] = useState<System>('metric')

  return (
    <>
      {recipes.map((recipe) => (
        <Recipe.Root
          key={recipe.id}
          recipe={recipe}
          system={system}
          onSystemChange={setSystem}
        >
          <h2>{recipe.name}</h2>
          <Recipe.SystemToggle />
        </Recipe.Root>
      ))}
    </>
  )
}

Every recipe starts in metric, and a click on any toggle switches them all. Each Root’s key is its recipe’s id, so recipes can’t hold two recipes with the same id: React warns about the duplicate keys in development, and once the list changes, it can show one recipe’s Root twice. MealPlan keeps the system in useState and passes a function to the Roots, so it starts with 'use client'.

setSystem from useRecipe() changes the same state as a click, so a control of your own stays in sync with the toggle.

Pass your state itself as system, not a value from useDeferredValue, and update it urgently in onSystemChange, not in a transition. Until the system you pass catches up, the toggle goes back to it: in MealPlan, after a click on US, Metric stays checked, a click on Metric does nothing, and the recipes still switch to US once the value catches up. To keep a slow part of the page from holding up the toggle, pass the deferred value to that part instead. On React 19, to save the system in a transition anyway, pass the value from useOptimistic, as Controlled and uncontrolled state shows.

Remember the reader’s choice

A Root doesn’t remember the reader’s system, so each page load starts it in the same system again. To keep the choice between visits and render it on the server, store it in a cookie: save it in onSystemChange, and read it with readRecipeView, which keeps only 'metric' or 'us'. This Next.js App Router page parses the Next.js example’s app/recipe.ts, which Render a recipe in React shows, and passes the saved system to a Client Component as defaultSystem:

app/recipes/pancakes/page.tsx
import { parseRecipe, readRecipeView } from '@recipe-book/react/core'
import { cookies } from 'next/headers'
import { pancakes } from '../../recipe'
import { SavedUnits } from './saved-units'

export default async function Page() {
  const result = parseRecipe(pancakes)
  if (!result.success) throw result.error
  const view = readRecipeView(result.data, {
    system: (await cookies()).get('recipe-system')?.value,
  })

  return <SavedUnits recipe={result.data} defaultSystem={view.system} />
}
app/recipes/pancakes/saved-units.tsx
'use client'

import {
  readRecipeView,
  type ParsedRecipe,
  type System,
} from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useSyncExternalStore } from 'react'

const readCookie = () =>
  document.cookie.match(/(?:^|; )recipe-system=([^;]*)/)?.[1]
const subscribe = () => () => {}

export function SavedUnits({
  recipe,
  defaultSystem,
}: {
  recipe: ParsedRecipe
  defaultSystem?: System | undefined
}) {
  const saved = useSyncExternalStore(subscribe, readCookie, () => defaultSystem)

  return (
    <Recipe.Root
      recipe={recipe}
      defaultSystem={readRecipeView(recipe, { system: saved }).system}
      onSystemChange={(system) => {
        document.cookie = `recipe-system=${system}; path=/; max-age=31536000; samesite=lax`
      }}
    >
      <Recipe.SystemToggle />
      <Recipe.Ingredients />
    </Recipe.Root>
  )
}

The server renders the saved system, so nothing changes once React hydrates the page, and the system stays uncontrolled. The cookie lasts a year. A missing cookie, or one that holds anything but 'metric' or 'us', is left out of the view, so the Root starts in its default system. If your next.config.ts sets cacheComponents: true, add a loading state next to the page, as Render a recipe in React does, or next build fails on the cookie read.

On Back or Forward, Next.js renders the page from its router cache with the defaultSystem it first had, so the Client Component reads the cookie as well. useSyncExternalStore returns defaultSystem on the server and while React hydrates the page, so the two renders match. Whenever the component mounts after that, as it does on Back unless cacheComponents: true kept the page mounted, it returns the cookie. The cookie changes only in onSystemChange, after the Root has read it, so subscribe listens for nothing. Share servings in a link reads servings from the URL with useSearchParams for the same reason.

To remember the reader’s units without a server, keep their choice in localStorage, and restore it with setSystem after the page loads:

TSX
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { startTransition, useEffect } from 'react'

function RestoreSystem() {
  const { setSystem } = Recipe.useRecipe()
  useEffect(() => {
    const saved = localStorage.getItem('recipe-system')
    if (saved === 'metric' || saved === 'us')
      startTransition(() => setSystem(saved))
  }, [setSystem])
  return null
}

export function Units({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root
      recipe={recipe}
      onSystemChange={(system) => localStorage.setItem('recipe-system', system)}
    >
      <RestoreSystem />
      <Recipe.SystemToggle />
    </Recipe.Root>
  )
}

The server can’t read localStorage, so the page renders in the Root’s starting system and switches to the saved one once React hydrates it. Reading the saved system during render, such as to pass it as defaultSystem, would render one system on the server and another in the browser: a hydration mismatch. Restoring from localStorage with setSystem keeps the system uncontrolled. Passing system only after the page loads would switch it from uncontrolled to controlled, which logs a development warning.

The restore is a transition so that, on React 18, Suspense boundaries inside the Root that haven’t hydrated yet, such as a lazy component or streamed data, hydrate first. Until the slowest one does, the page stays in its starting system. An urgent update makes React 18 report error #421, throw away those boundaries’ server HTML, and render them in the browser. React 19 doesn’t wait, whether or not the restore is a transition: the toggle switches to the saved system at once, and a boundary that hasn’t hydrated yet keeps its server HTML, in the starting system, until it hydrates, so the page can show “1 cup flour” with Metric checked. The boundary hydrates in the starting system, then switches to the saved one. With a server, the cookie version above has none of this.

In a form

The toggle renders buttons, not form fields, so a form doesn’t send the system. To send it, render <input type="hidden" name="system" value={Recipe.useRecipe().system} /> in a component inside the Root. The form then sends metric or us, the system the toggle shows.

Labels

Set the system, metric, and us labels with labels on the Root or a provider, in a pack from labelPack. Make the pack once, in a 'use client' module:

TSX
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { labelPack } from '@recipe-book/react/labels'

const labels = labelPack({
  system: 'Sistema de medida',
  metric: 'Métrico',
  us: 'EE. UU.',
})

export function Unidades({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe} labels={labels}>
      <Recipe.SystemToggle />
    </Recipe.Root>
  )
}

For the sample recipe, Unidades renders:

HTML
<div aria-label="Sistema de medida" role="radiogroup" data-recipe-system-toggle="">
  <button autoComplete="off" type="button" role="radio" aria-checked="false" tabindex="-1" data-recipe-system-option="" data-state="unchecked">Métrico</button>
  <button autoComplete="off" type="button" role="radio" aria-checked="true" tabindex="0" data-recipe-system-option="" data-state="checked">EE. UU.</button>
</div>

Render your own elements

With asChild, each part renders its one element child instead of its own element, and passes its props to it, including its role, ARIA attributes, data-recipe-* attributes, and ref. A prop set on the child wins, except that the classNames join, the style objects merge key by key with the child’s value winning, both event handlers run, and the part’s tabIndex wins, so the options keep one tab stop. The child’s handler runs first. A handler that the child sets to undefined leaves the part’s in place, and so does a className, style, or ref set to undefined. Any other prop that the child sets to undefined wins too, and removes the part’s value. A ref on the child gets the element too.

So a <button role={undefined}> child of <Recipe.SystemOption> renders without role="radio". A component that passes its own optional props, such as type, role, autoComplete, or aria-* attributes, on to the child should leave out each one it has no value for, such as with {...(role === undefined ? {} : { role })}, rather than pass undefined.

For <Recipe.SystemOption>, render a <button> or a component that renders one, so Space and Enter check it, and a disabled option reads as disabled to screen readers and doesn’t take focus on a click. A disabled set on the child disables the option as the option’s own disabled does: a click doesn’t select it, the arrow keys skip it, and it gives up the tab stop.

The child’s own children take the place of the part’s, so an element child, other than a Fragment, whose children are undefined, null, true, or false gets the part’s defaults, but '', [], or an empty Fragment render nothing. Here, each Segment with no children shows its option’s label:

TSX
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import type { ComponentProps } from 'react'

function SegmentedControl(props: ComponentProps<'div'>) {
  return <div className="segmented-control" {...props} />
}

function Segment(props: ComponentProps<'button'>) {
  return <button className="segment" {...props} />
}

export function Units({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.SystemToggle asChild>
        <SegmentedControl>
          <Recipe.SystemOption value="metric" asChild>
            <Segment />
          </Recipe.SystemOption>
          <Recipe.SystemOption value="us" asChild>
            <Segment />
          </Recipe.SystemOption>
        </SegmentedControl>
      </Recipe.SystemToggle>
    </Recipe.Root>
  )
}

For the sample recipe, Units renders:

HTML
<div class="segmented-control" aria-label="Measurement system" role="radiogroup" data-recipe-system-toggle="">
  <button class="segment" autoComplete="off" type="button" role="radio" aria-checked="false" tabindex="-1" data-recipe-system-option="" data-state="unchecked">Metric</button>
  <button class="segment" autoComplete="off" type="button" role="radio" aria-checked="true" tabindex="0" data-recipe-system-option="" data-state="checked">US</button>
</div>

A toggle child whose children are undefined, null, true, or false gets the metric and US options the same way, so <Recipe.SystemToggle asChild><SegmentedControl /></Recipe.SystemToggle> renders both inside the segmented-control div, as plain <button>s.

On React 18, a function component gets a ref only through forwardRef, so a child component, such as SegmentedControl or Segment, must use it to pass the ref to its element. Otherwise, a ref on the part doesn’t reach the element, and in development React warns that function components cannot be given refs.

asChild needs one element child. With anything else, such as no children, text, several children, or a Fragment, the part renders its own <div> or <button> instead, with those children, or with its defaults when they’re undefined, null, true, or false. In development, the first <Recipe.SystemToggle> and the first <Recipe.SystemOption> to do this each log a development warning.

Style with data attributes

The group has data-recipe-system-toggle, and each option has data-recipe-system-option and data-state. Both have data-disabled while they’re disabled. Style a recipe lists every data attribute that the parts set. This CSS bolds the checked option and dims a disabled toggle:

CSS
[data-recipe-system-option][data-state='checked'] {
  font-weight: 600;
}

[data-recipe-system-toggle][data-disabled] {
  opacity: 0.5;
}

Errors

Each part throws missing_parent when it isn’t inside its parent. <Recipe.SystemToggle> must be inside <Recipe.Root>:

Text
RecipeBookError: <Recipe.SystemToggle> must be rendered inside <Recipe.Root>.
See https://recipe-book.siraj.page/errors/missing_parent/

<Recipe.SystemOption> must be inside <Recipe.SystemToggle>. Outside a toggle, it throws this message whether or not it’s inside a Root:

Text
RecipeBookError: <Recipe.SystemOption> must be rendered inside <Recipe.SystemToggle>.
See https://recipe-book.siraj.page/errors/missing_parent/

Types

@recipe-book/react exports each part’s props type: RecipeSystemToggleProps and RecipeSystemOptionProps. Use them to type a component that wraps a part:

TSX
import * as Recipe from '@recipe-book/react'

export function Units(props: Recipe.RecipeSystemToggleProps) {
  return <Recipe.SystemToggle className="units" {...props} />
}

Named imports

To import these parts by name, import each one without the Recipe.: SystemToggle and SystemOption. If a name clashes with one of yours, alias it, as in import { SystemToggle as RecipeSystemToggle } from '@recipe-book/react'.

Contents