Recipe Book0.6.0

2.10Guides

Make a recipe accessible

See what the React parts give screen reader and keyboard users, then translate their labels, name controls, set heading levels, and choose alt text.

§ 2.1014 min readView as Markdown

Build a recipe page that supports screen reader and keyboard users: the @recipe-book/react parts render native elements with the roles, names, and keyboard navigation they expect.

What the parts give you

The Next.js example renders the sample recipe with the parts:

app/page.tsx
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import NextImage from 'next/image'
import { pancakes } from './recipe'

export default function Page() {
  const result = parseRecipe(pancakes)
  if (!result.success) throw result.error

  return (
    <main>
      <Recipe.Root recipe={result.data}>
        <Recipe.Image as={NextImage} alt="" width={600} height={400} preload />
        <h1>{result.data.name}</h1>
        <Recipe.ServingsSelect />
        <Recipe.SystemToggle />
        <h2>Ingredients</h2>
        <Recipe.Ingredients />
        <h2>Steps</h2>
        <Recipe.Steps />
        <Recipe.JsonLd url="https://example.com/" />
      </Recipe.Root>
    </main>
  )
}

To run this page in your app, also save the example’s image, which Render a recipe in React shows, as public/pancakes.svg. Before Next.js 16, change the preload prop to priority, or next build fails its type check. Without Next.js, as in a Vite app, delete the next/image import and the as={NextImage} and preload props from <Recipe.Image>, which then renders an <img>.

Screen readers read a page from the browser’s accessibility tree. In Chrome’s, the example’s parts appear as:

Part Role Accessible name
<Recipe.Image alt="" /> None, because the image is left out None
<Recipe.ServingsSelect /> combobox, whose value is the selected option, “4 servings” “Servings”
<Recipe.ServingsInput />, in the select’s place spinbutton, whose value is the number, 4 “Servings”
<Recipe.SystemToggle /> radiogroup “Measurement system”
Each of the toggle’s options radio, checked or not checked “Metric” and “US”
<Recipe.Ingredients /> list, with a listitem for each ingredient None
<Recipe.Steps /> list, with a numbered listitem for each step None

The headings “Buttermilk pancakes”, “Ingredients”, and “Steps” are the page’s own.

The example doesn’t render <Recipe.Times>, <Recipe.Equipment>, <Recipe.Notes>, or <Recipe.Nutrition>. In Chrome’s tree, Times and Nutrition are description lists, with a term and a definition for each row, such as “Prep time” and “10 min”. Equipment is a list with a listitem for each tool, and Notes gives each note’s text as a paragraph, after its title as a heading. None of the four renders a heading above itself, and each renders nothing when the recipe has nothing for it to show, so render your heading only when the recipe does, or the heading has nothing under it.

Nor does the example render <Recipe.CookMode>, a switch in Chrome’s tree, checked or not checked, named “Keep screen on” by the cookMode label. The server can’t tell whether the browser can keep the screen on, so until React hydrates the page, the switch is disabled, and Chrome’s tree shows “Keep screen on” as a switch that’s not checked and unavailable. Once React hydrates the page, the switch is enabled in a browser that can keep the screen on, and gone in one that can’t, such as a browser on a page served over plain HTTP from anywhere but localhost.

No part is a live region. When a reader changes the servings or the system, the control in Chrome’s tree takes its new value, such as “8 servings”, but nothing announces the new quantities, which the reader reaches on moving to the ingredients.

The step numbers come from the list’s markers. CSS that removes the markers, as the Tailwind CSS reset in a new create-next-app project does, also takes the numbers out of the accessibility tree, so screen readers don’t announce them. To keep them, show the markers again:

CSS
[data-recipe-step-list] {
  list-style: decimal;
  padding-inline-start: 1.5rem;
}

In Safari, removing the markers also changes the lists’ role: WebKit, Safari’s engine, exposes a <ul> or <ol> without a role as a list only when one of its items shows a marker, and as a group otherwise. The CSS above keeps the steps a list. To keep the ingredients one too, show their markers:

CSS
[data-recipe-ingredient-list] {
  list-style: disc;
  padding-inline-start: 1.5rem;
}

To keep the ingredients without bullets instead, render <Recipe.IngredientList> yourself in <Recipe.Ingredients>’s children and pass it role="list". WebKit exposes an element with that role as a list whether or not its items show markers.

The parts don’t size their controls either. In Chrome with no CSS, the measurement system options, the servings input, and the CookMode switch are about 21 pixels tall, and the servings select about 19. WCAG 2.2’s target size criterion asks for 24 by 24 pixels unless a smaller target has enough space around it. axe’s target-size rule passes the controls when they sit side by side. With the servings control directly above or below an option, as in the examples without their CSS, axe flags the option if it’s checked. If the option isn’t checked, axe lists it for review, asking “Is this a target?”, since an unchecked option has tabindex="-1". A select spans both options and is flagged too. The input isn’t flagged, and in the Vite example it sits over only the second option, after its label text. A default axe.run() skips target-size, as does runOnly with the wcag2a, wcag2aa, and wcag21aa tags. It runs when runOnly includes the wcag22aa or wcag258 tag, or when you enable the rule.

Give the controls a minimum height, as the Vite example’s src/styles.css, in Style a recipe, does for the servings input and the options. The second rule here sizes the checkboxes of a <Recipe.Checklist>, and the third spaces the links of a <Recipe.Equipment>:

CSS
[data-recipe-servings-select],
[data-recipe-servings-input],
[data-recipe-system-option],
[data-recipe-cook-mode] {
  min-height: 24px;
}

[data-recipe-ingredient-checkbox],
[data-recipe-step-checkbox] {
  min-width: 24px;
  min-height: 24px;
}

[data-recipe-equipment-item] {
  min-height: 24px;
}

With no CSS, Chrome draws the checkboxes 13 pixels square, in rows 20 pixels apart. axe’s target-size rule doesn’t check them, because each sits in a line of text, so a pass says nothing about them. They need a minimum width as well: with only a minimum height, Chrome makes each checkbox 24 pixels tall but still draws a 13-pixel box in the middle of that height, which sits higher than the line’s text.

A tool in <Recipe.Equipment> with a url shows its name as a link. The link is a tab stop, named by the tool’s name alone, so the link in “1 rack” is named “rack”. axe does check a link that’s all its item shows: with no CSS, it’s 17 pixels tall, in rows 18 pixels apart, so axe flags it. The minimum height on each item puts the rows 24 pixels apart, and axe passes the links for their spacing, though they stay 17 pixels tall. The rack’s link follows its quantity, in a line of text, so axe doesn’t check it.

Translate the built-in text

The parts take their names, a few words they show, and the words for units from labels. To translate them for an app in another language (i18n), pass a label pack as labels to a <Recipe.Provider> in the layout of the routes that render recipes, not in app/layout.tsx, and set lang on <html> in app/layout.tsx to the same language, so screen readers read the page in it. A layout can pass es itself, as in Label packs, but this pack adds the terms es leaves out, so the provider renders from a 'use client' module that makes it with labelPack.

app/recipes/recipe-provider.tsx
'use client'

import * as Recipe from '@recipe-book/react'
import { es, labelPack } from '@recipe-book/react/labels'
import type { ReactNode } from 'react'

const spanish = labelPack({
  ...es,
  prepTime: 'Preparación',
  cookTime: 'Cocción',
  totalTime: 'Tiempo total',
  servingSize: 'Tamaño de la ración',
  calories: 'Calorías',
  fat: 'Grasas',
  saturatedFat: 'Grasas saturadas',
  transFat: 'Grasas trans',
  unsaturatedFat: 'Grasas insaturadas',
  carbohydrates: 'Hidratos de carbono',
  sugar: 'Azúcares',
  fiber: 'Fibra alimentaria',
  protein: 'Proteínas',
  sodium: 'Sodio',
  cholesterol: 'Colesterol',
  cookMode: 'Mantener la pantalla encendida',
})

export function RecipeProvider({ children }: { children: ReactNode }) {
  return (
    <Recipe.Provider locale="es-ES" labels={spanish}>
      {children}
    </Recipe.Provider>
  )
}
app/recipes/layout.tsx
import type { ReactNode } from 'react'
import { RecipeProvider } from './recipe-provider'

export default function RecipesLayout({ children }: { children: ReactNode }) {
  return <RecipeProvider>{children}</RecipeProvider>
}

In a single-page app, such as a Vite app, put the provider in src/main.tsx, around <App />, and set lang="es" on <html> in index.html.

With the example page moved under the provider, such as to app/recipes/pancakes/page.tsx with its './recipe' import changed to '../../recipe', it names its select “Raciones”, with options such as “4 raciones”, and names its toggle “Sistema de medición”, with the radios “Métrico” and “EE. UU.”. It writes “2 cucharadas” for the sugar’s 2 tbsp, but still “1 ½ cups” for the flour, because US units such as cups keep their English names in every pack, as What a pack holds explains.

For a language with no pack, write every label yourself in the object that you pass to labelPack, and check that object with satisfies Recipe.RecipeLabels, so TypeScript reports a missing key of the controls’ text. It doesn’t report a missing language, units, durations, temperature, or size, which are optional and fall back to English, so write those too. RecipeLabels describes each label.

The recipe’s name, ingredients, and steps come from its author, so translate them in the recipe input. Its equipment, its notes, its custom times’ labels, and the serving size in its nutrition facts come from its author too. The durations of <Recipe.Times> keep English unit words, so with spanish, a total time of 210 minutes has the term “Tiempo total” but reads “3 hr 30 min”.

Name controls to match your layout

The servings label names the servings controls, and system names the toggle. When your layout shows its own text for a control, name the control with that text, so what readers see matches what screen readers say:

app/recipe-controls.tsx
import * as Recipe from '@recipe-book/react'

export function RecipeControls() {
  return (
    <>
      <label htmlFor="servings">Serves</label>
      <Recipe.ServingsSelect id="servings" aria-label="" />
      <span id="units">Units</span>
      <Recipe.SystemToggle aria-labelledby="units" />
    </>
  )
}

For the sample recipe, RecipeControls renders this HTML, indented here for reading:

HTML
<label for="servings">Serves</label>
<select autoComplete="off" id="servings" data-recipe-servings-select="">
  <option value="2">2 servings</option>
  <option value="4" selected="">4 servings</option>
  <option value="8">8 servings</option>
  <option value="12">12 servings</option>
</select>
<span id="units">Units</span>
<div aria-labelledby="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>

In the example page, render <RecipeControls /> inside <Recipe.Root> in place of the select and the toggle. aria-label="" keeps the select from setting its own aria-label, which would outrank the <label>, and on the toggle, aria-labelledby outranks the default aria-label, because the <span> it names has text.

<Recipe.ServingsInput> takes the same props, and needs visible text more than the select does: the select’s options say what they count, such as “4 servings”, but the input shows only a number. ServingsField gives it a label.

In a <Recipe.Checklist>, a <label> around each ingredient’s or step’s line names its checkbox with the line as the page shows it. In Chrome, the flour’s checkbox is named “1 ½ cups all-purpose flour”, or “190 g all-purpose flour” in metric. A quantity range reads with the to label, as in “1 to 2 lemons, zested”, and an optional ingredient ends with the optional label, as in “½ tsp chili flakes (optional)”. For a step, that’s its name, if it has one, then its text, without the number, which comes from the list’s marker. When you render an ingredient or step yourself, put <Recipe.IngredientCheckbox> or <Recipe.StepCheckbox> in a <label> with the text it ticks, so the box keeps a name.

Choose alt text

<Recipe.Image> takes its alt text from the recipe’s name, so without alt, screen readers announce an image named “Buttermilk pancakes”. When a heading next to it already names the recipe, as the example’s <h1> does, pass alt="" so screen readers don’t read the name twice. See Decorative images.

Read ranges aloud

In <Recipe.Ingredients>, the dash of a quantity range, as in “2–3 tbsp”, is marked aria-hidden="true" and followed by the to label in text that’s hidden on screen, so in Chrome and Firefox the label takes the dash’s place. A size’s range, as in “2 cans (425–454 g each)”, keeps a plain dash. For an ingredient written as { name: 'lemon', plural: 'lemons', quantity: '1–2', note: 'zested' }, the page shows 1–2 lemons, zested.

In Chrome’s accessibility tree, the list item has no dash, and “ to “ is a separate piece of text between “1” and “2”, so Chrome names a link inside the list item, around this ingredient, “1 to 2 lemons, zested”. Firefox and WebKitGTK name that link the same, but the text WebKitGTK gives screen readers for the list item and the link keeps the dash, as “1– to 2 lemons, zested”. Chrome gives a link around the whole list the same name, but Firefox starts that name with the list’s marker, as in “• 1 to 2 lemons, zested”, when the list shows one, and WebKitGTK gives the link no name.

Only the ingredient parts do this. The step parts show a step’s words as written, converting only its temperatures and, in <Recipe.ConvertedStepText>, its amounts, and keep a range’s dash. So “2–3 minutes” in a step reaches screen readers with its dash, as does “1–2 cups of milk”, which <Recipe.ConvertedStepText> shows in metric as “237–473 mL of milk”, and so does the text that useFormatIngredient() returns. A temperature range in a step keeps its dash too: “180–200°C” isn’t converted, and “180°C–200°C” converts each end and keeps the dash between them. <Recipe.ServingsText> and <Recipe.YieldText> keep a range’s dash as well, as in “6–8 servings”. To keep the to label in an ingredient you render in your own markup, put <Recipe.IngredientQuantity> in that markup.

Set heading levels

<Recipe.Ingredients> and <Recipe.Steps> render a titled section as a <section> headed by its title, so screen readers can jump to it by its heading. The heading is an <h3> by default, to sit under an <h2> such as the example’s “Ingredients”. When your page puts the recipe a level deeper, pass headingLevel to keep the outline in order:

app/recipe-card.tsx
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function RecipeCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <h2>{recipe.name}</h2>
      <h3>Ingredients</h3>
      <Recipe.Ingredients headingLevel={4} />
      <h3>Steps</h3>
      <Recipe.Steps headingLevel={4} />
    </Recipe.Root>
  )
}

For the sample recipe with its maple syrup moved to a section titled “To serve”, RecipeCard renders this HTML, indented here for reading:

HTML
<h2>Buttermilk pancakes</h2>
<h3>Ingredients</h3>
<div data-recipe-ingredients="">
  <div data-recipe-ingredient-section="">
    <ul data-recipe-ingredient-list="">
      <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">1 ½ cups</span> <span data-recipe-ingredient-name="">all-purpose flour</span></li>
      <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2 tbsp</span> <span data-recipe-ingredient-name="">sugar</span></li>
      <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2 tsp</span> <span data-recipe-ingredient-name="">baking powder</span></li>
      <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">1 ¼ cups</span> <span data-recipe-ingredient-name="">buttermilk</span></li>
      <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2</span> <span data-recipe-ingredient-name="">eggs</span></li>
      <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">3 tbsp</span> <span data-recipe-ingredient-name="">butter</span>, <span data-recipe-ingredient-note="">melted</span></li>
    </ul>
  </div>
  <section data-recipe-ingredient-section="">
    <h4>To serve</h4>
    <ul data-recipe-ingredient-list="">
      <li data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span>, <span data-recipe-ingredient-note="">to serve</span></li>
    </ul>
  </section>
</div>
<h3>Steps</h3>
<div data-recipe-steps="">
  <div data-recipe-step-section="">
    <ol start="1" data-recipe-step-list="">
      <li id="buttermilk-pancakes-step-1" data-recipe-step=""><span data-recipe-step-text="">Whisk the dry ingredients in a large bowl.</span></li>
      <li id="buttermilk-pancakes-step-2" data-recipe-step=""><span data-recipe-step-text="">Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.</span></li>
      <li id="buttermilk-pancakes-step-3" data-recipe-step=""><span data-recipe-step-text="">Cook ¼-cup portions on a buttered griddle, <span data-recipe-duration="">2–⁠3 minutes</span> per side.</span></li>
    </ol>
  </div>
</div>

<Recipe.Notes> takes headingLevel too, for the titles of its notes, which are headings but not sections.

RecipeHeadingLevel lists the levels.

Use the keyboard

The measurement system toggle is one tab stop, as a radio group is, and the arrow keys move focus between its options and check them. In the example, Tab from the servings select focuses US, the recipe’s own system, and Right Arrow wraps to Metric, switching the ingredients to metric. When the recipe has nothing to convert, the toggle is disabled, so Tab skips it. Keyboard lists every key.

The checkboxes of a <Recipe.Checklist> are native, each its own tab stop, so Tab moves through them line by line, and Space ticks or unticks the one in focus. With a Checklist around the example’s lists, Tab from US focuses the flour’s checkbox, then each ingredient’s and step’s in turn, 10 tab stops in all. To leave a list’s checkboxes and their tab stops out, pass it checkboxes={false}.

<Recipe.CookMode> renders a <button>, so it’s one tab stop, and Space or Enter turns it on or off. With the switch after the toggle in the example, Tab from US focuses it, and Space turns it on, which Chrome’s tree shows as checked. Tab skips the disabled switch until the page hydrates, and in a browser that can’t keep the screen on, there’s no switch to reach after it does.

The parts don’t style their controls, so their focus rings are the browser’s. An option an arrow key focuses matches :focus-visible, as one that Tab reaches does, so if you restyle the options, keep a visible outline on [data-recipe-system-option]:focus-visible.

Both servings controls are native form elements, so the browser handles their keys. In <Recipe.ServingsInput>, Up Arrow and Down Arrow change the number by step, setting servings each time. Typing sets servings at each number the input accepts, so with the default step, typing 1.5 sets servings to 1 and leaves them there. The 1.5 is off the step grid, so the browser marks the input invalid, and Chrome tells screen readers so. Pass step={0.5} to accept halves, or step="any" to accept any number.

Nothing on the page says which numbers the input accepts, and when the input loses focus, it shows the current servings again, so a number it didn’t accept disappears. Say which numbers it accepts in text next to it, and point aria-describedby at the text, so screen readers read the text as the input’s description. Give the input a label too, with aria-label="" so the label names it. While the number typed in it isn’t applied, the example sets aria-invalid on the input and starts the text with “Not applied.”, so a number it didn’t accept doesn’t look applied:

app/servings-field.tsx
'use client'

import { useId, useState } from 'react'
import * as Recipe from '@recipe-book/react'

export function ServingsField() {
  const { servings } = Recipe.useRecipe()
  const [typed, setTyped] = useState<string>()
  const id = useId()
  const unapplied = typed !== undefined && Number(typed) !== servings
  return (
    <>
      <label htmlFor={id}>Servings</label>
      <Recipe.ServingsInput
        id={id}
        aria-label=""
        max={48}
        aria-describedby={`${id}-hint`}
        aria-invalid={unapplied || undefined}
        onChange={(event) => setTyped(event.target.value)}
        onBlur={() => setTyped(undefined)}
      />
      <p id={`${id}-hint`}>
        {unapplied && (
          <>
            <strong>Not applied.</strong>{' '}
          </>
        )}
        Whole numbers from 1 to 48
      </p>
    </>
  )
}

For the sample recipe, on React 19.2 or later, ServingsField renders this HTML as the first part in <Recipe.Root>, with one element per line here for reading:

HTML
<label for="_R_0_">Servings</label>
<input autoComplete="off" id="_R_0_" aria-describedby="_R_0_-hint" type="number" inputMode="numeric" min="1" max="48" data-recipe-servings-input="" value="4"/>
<p id="_R_0_-hint">Whole numbers from 1 to 48</p>

Render <ServingsField /> inside <Recipe.Root>, such as where the example page has its select. useId gives each field its own ids, so on a page with two Roots, each label and description belongs to its own Root’s input. The ids depend on React’s version and the field’s place in the tree: React 18 and 19.0 write :R0: (:R2: after a <Recipe.ServingsText> in the same Root), React 19.1 writes «R0» («R2»), and React 19.2 or later writes _R_0_ (_R_2_). Keep the text in step with the input’s min, max, and step.

Next steps

  • Servings for the servings controls, their names, and the step grid
  • SystemToggle for the toggle, its keyboard behavior, and when it’s disabled
  • Ingredients for sections, ranges, and the optional and to labels
  • Checklist for the checkboxes, placing your own, and lists without them
  • CookMode for the switch, when it’s disabled, and browsers that can’t keep the screen on
  • Image for alt text and rendering your own image component
  • Provider for every label and how labels merge
Contents