Recipe Book0.6.0

4.5React reference

Ingredients

Reference for <Recipe.Ingredients>, <Recipe.IngredientList>, <Recipe.Ingredient>, and its sub-parts, which render scaled, converted ingredients.

§ 4.522 min readView as Markdown

Seven parts render a recipe’s ingredients at the reader’s servings and in their measurement system, from the list of sections down to each ingredient’s quantity, name, note, and optional label.

Whole numbers from 1 to 4,000,000

  • 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

Anatomy

TSX
'use client'

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

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Ingredients>
        {(section) => (
          <Recipe.IngredientList section={section}>
            {(item) => (
              <Recipe.Ingredient item={item}>
                <Recipe.IngredientQuantity />
                <Recipe.IngredientName />
                <Recipe.IngredientNote />
                <Recipe.IngredientOptional />
              </Recipe.Ingredient>
            )}
          </Recipe.IngredientList>
        )}
      </Recipe.Ingredients>
    </Recipe.Root>
  )
}

Every part must be inside <Recipe.Root>, and the four sub-parts must be inside a <Recipe.Ingredient>. The rest is optional: <Recipe.IngredientList> works without <Recipe.Ingredients>, <Recipe.Ingredient> works without a list part, and a part without children renders its default content. To format ingredients as text instead, call useFormatIngredient(). Inside a <Recipe.Checklist>, each ingredient’s default content follows a checkbox, so readers can tick off the ingredients as they gather them. Children like the ones above replace the checkbox too, so put an <Recipe.IngredientCheckbox> in them.

Ingredients

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

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  servings: 4,
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
    { name: 'buttermilk', quantity: '1 ¼ cups' },
    { name: 'egg', plural: 'eggs', quantity: 2 },
    { name: 'butter', quantity: '3 tbsp', note: 'melted' },
    {
      title: 'To serve',
      items: [
        { name: 'blueberries', quantity: '1 cup', optional: true },
        { name: 'maple syrup' },
      ],
    },
  ],
  steps: ['Whisk the batter, then cook it on a buttered griddle.'],
})
if (!result.success) throw result.error
const recipe = result.data

export function IngredientsCard() {
  return (
    <Recipe.Root recipe={recipe}>
      <h2>Ingredients</h2>
      <Recipe.Ingredients />
    </Recipe.Root>
  )
}

IngredientsCard renders this HTML, indented here for reading:

HTML
<h2>Ingredients</h2>
<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="">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="">
    <h3>To serve</h3>
    <ul data-recipe-ingredient-list="">
      <li data-recipe-ingredient="" data-origin="authored" data-optional=""><span data-recipe-ingredient-quantity="">1 cup</span> <span data-recipe-ingredient-name="">blueberries</span> <span data-recipe-ingredient-optional="">(optional)</span></li>
      <li data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
    </ul>
  </section>
</div>

<Recipe.Ingredients> renders a <div> with one block for each of the recipe’s ingredient sections that has ingredients. A titled section is a <section> headed by its title, so screen readers can jump to it by its heading. It has no accessible name, so it isn’t a region landmark, and an ingredient section and a step section that share a title, such as “Crust”, don’t make two landmarks with one name. An untitled section, or one whose title is '', is a plain <div> with no heading. A section with no ingredients has no block, title and all, and <Recipe.Ingredients> renders nothing when no section has ingredients, so hide a heading above it unless one does.

Name Type Description
headingLevel RecipeHeadingLevel | undefined The heading level of section titles in the default rendering. Defaults to 3, for ingredients under an <h2> as in the example. See Set heading levels.
checkboxes boolean | undefined Inside a <Recipe.Checklist>, whether each ingredient has a checkbox. Defaults to the checkboxes of a list around it, or to true. See Lists without checkboxes.
children ((section: RecipeSection<RecipeIngredientItem>) => ReactNode) | undefined Renders each section instead of the default: a <section> headed by the section’s title, or a <div> for an untitled section, around a <Recipe.IngredientList> of its ingredients. See Render your own sections.

Any other <div> prop, such as className or aria-label, passes to the <div>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML. Style the parts with className, or select their data-recipe-* attributes. Style a recipe lists every data attribute that the parts set.

Render your own sections

The children function receives a RecipeSection of RecipeIngredientItems, for every section, including one with no ingredients. For that section, a <Recipe.IngredientList> renders nothing, but a heading you render stays: return null when the section’s items is empty to leave it out, as the default does. <Recipe.Ingredients> renders nothing only when the recipe has no sections. It keys each result by the section’s id, so an element or fragment you return needs no key. If you return an array, each of its elements needs its own key, as in any React list. A function can’t cross from a Server Component to a Client Component, so the file that passes it starts with 'use client':

TSX
'use client'

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

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Ingredients>
        {(section) => (
          <div className="group">
            <h3>{section.title ?? 'Batter'}</h3>
            <Recipe.IngredientList section={section} />
          </div>
        )}
      </Recipe.Ingredients>
    </Recipe.Root>
  )
}

For the recipe in the first example, IngredientsCard renders:

HTML
<div data-recipe-ingredients="">
  <div class="group">
    <h3>Batter</h3>
    <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="">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>
  <div class="group">
    <h3>To serve</h3>
    <ul data-recipe-ingredient-list="">
      <li data-recipe-ingredient="" data-origin="authored" data-optional=""><span data-recipe-ingredient-quantity="">1 cup</span> <span data-recipe-ingredient-name="">blueberries</span> <span data-recipe-ingredient-optional="">(optional)</span></li>
      <li data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
    </ul>
  </div>
</div>

Without 'use client', IngredientsCard runs as a Server Component when a page imports it, and rendering fails. In development, React reports:

Text
Error: Functions are not valid as a child of Client Components. This may happen if you return children instead of <children /> from render. Or maybe you meant to call this function rather than return it.
  <... children={function children}>
                ^^^^^^^^^^^^^^^^^^^

In production, React reports a different message, which next build prints when it prerenders the page:

Text
Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
  {children: function children}
             ^^^^^^^^^^^^^^^^^

IngredientList

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

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.IngredientList className="ingredients" />
    </Recipe.Root>
  )
}

For the recipe in the first example, IngredientsCard renders one list:

HTML
<ul class="ingredients" 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="">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>
  <li data-recipe-ingredient="" data-origin="authored" data-optional=""><span data-recipe-ingredient-quantity="">1 cup</span> <span data-recipe-ingredient-name="">blueberries</span> <span data-recipe-ingredient-optional="">(optional)</span></li>
  <li data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
</ul>

It renders a <ul> with a <Recipe.Ingredient> for each ingredient, or nothing when it has no ingredients to list, such as for a section with none.

Name Type Description
section RecipeSection<RecipeIngredientItem> | undefined The section to list, such as the one <Recipe.Ingredients> passes to its children. Defaults to every ingredient in the recipe.
children ((item: RecipeIngredientItem) => ReactNode) | undefined Renders each ingredient instead of the default, <Recipe.Ingredient item={item} />. See Render your own ingredients.
checkboxes boolean | undefined Inside a <Recipe.Checklist>, whether each ingredient has a checkbox. Defaults to the checkboxes of a list around it, or to true. See Lists without checkboxes.

Any other <ul> prop passes to the <ul>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML.

Render your own ingredients

Pass a function as children from a Client Component, as with <Recipe.Ingredients>. It receives a RecipeIngredientItem, and <Recipe.IngredientList> keys each result by the item’s id. Render a <Recipe.Ingredient> to keep the <li> and its content, such as with an id that a step can link to:

TSX
'use client'

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

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.IngredientList>
        {(item) => (
          <Recipe.Ingredient item={item} id={`ingredient-${item.id}`} />
        )}
      </Recipe.IngredientList>
    </Recipe.Root>
  )
}
HTML
<ul data-recipe-ingredient-list="">
  <li id="ingredient-all-purpose-flour" 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 id="ingredient-buttermilk" data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">1 ¼ cups</span> <span data-recipe-ingredient-name="">buttermilk</span></li>
  <li id="ingredient-egg" data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2</span> <span data-recipe-ingredient-name="">eggs</span></li>
  <li id="ingredient-butter" 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>
  <li id="ingredient-blueberries" data-recipe-ingredient="" data-origin="authored" data-optional=""><span data-recipe-ingredient-quantity="">1 cup</span> <span data-recipe-ingredient-name="">blueberries</span> <span data-recipe-ingredient-optional="">(optional)</span></li>
  <li id="ingredient-maple-syrup" data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
</ul>

Ingredient

TSX
'use client'

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

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.IngredientList>
        {(item) => (
          <Recipe.Ingredient item={item} className="ingredient">
            <Recipe.IngredientQuantity className="quantity" />
            <Recipe.IngredientName />
            <Recipe.IngredientNote className="note" />
            <Recipe.IngredientOptional />
          </Recipe.Ingredient>
        )}
      </Recipe.IngredientList>
    </Recipe.Root>
  )
}

For the recipe in the first example, IngredientsCard renders:

HTML
<ul data-recipe-ingredient-list="">
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">1 ½ cups</span><span data-recipe-ingredient-name="">all-purpose flour</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">1 ¼ cups</span><span data-recipe-ingredient-name="">buttermilk</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">2</span><span data-recipe-ingredient-name="">eggs</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">3 tbsp</span><span data-recipe-ingredient-name="">butter</span><span class="note" data-recipe-ingredient-note="">melted</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored" data-optional=""><span class="quantity" data-recipe-ingredient-quantity="">1 cup</span><span data-recipe-ingredient-name="">blueberries</span><span data-recipe-ingredient-optional="">(optional)</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
</ul>

Your children replace the default content, and the spaces and commas between the sub-parts go with it, so lay the sub-parts out with CSS, such as a grid with the quantities in one column.

<Recipe.Ingredient> renders an <li>. Without children, or when children is null, undefined, true, or false, it renders the four sub-parts. It joins the first three as formatIngredient’s text does, then adds a space and the optional label, which text leaves out. A sub-part with nothing to show renders nothing, and so does its separator, as the first example shows.

It always sets data-recipe-ingredient. When the ingredient has a quantity, data-origin says where the quantity comes from: authored, equivalent, or converted, as QuantityOrigin describes. An ingredient without a quantity has data-unquantified instead, and an optional ingredient also has data-optional.

Name Type Description
item RecipeIngredientItem The ingredient to render, such as one that <Recipe.IngredientList> passes to its children.
asChild boolean | undefined Renders the ingredient as its only child instead of an <li>. See Render your own element. Defaults to false.
children ReactNode | undefined The content of the <li>. Defaults to the four sub-parts and the separators between them. Inside a <Recipe.Checklist>, those follow an <Recipe.IngredientCheckbox> and a space, in a <label>, unless a list around the ingredient has checkboxes={false}.

Any other <li> prop passes to the <li>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML. <Recipe.Ingredient> formats item with Root’s locale and labels. Inside a Checklist, the <li> of a ticked ingredient has data-checked, whatever its children.

Render your own element

With asChild, <Recipe.Ingredient> passes its data-* attributes, your other props, and its ref to its only child. Use it for a component that must be the list item itself, such as an animated motion.li. Render an <li> or a component that renders one, so the list keeps its items. Its props and ref merge with the child’s as asChild on the system toggle describes, along with what a function component needs on React 18.

The child’s children are the ingredient’s content. A child whose children are undefined, null, true, or false, such as <motion.li layout />, gets the default content, but any other children replace it, even '', [], or an empty Fragment, which render nothing. Here, Row stands in for a component like that:

TSX
'use client'

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

function Row(props: ComponentProps<'li'>) {
  return <li {...props} />
}

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.IngredientList>
        {(item) => (
          <Recipe.Ingredient item={item} asChild className="ingredient">
            <Row className="row" />
          </Recipe.Ingredient>
        )}
      </Recipe.IngredientList>
    </Recipe.Root>
  )
}

For the recipe in the first example, IngredientsCard renders:

HTML
<ul data-recipe-ingredient-list="">
  <li class="ingredient row" 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 class="ingredient row" data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">1 ¼ cups</span> <span data-recipe-ingredient-name="">buttermilk</span></li>
  <li class="ingredient row" data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">2</span> <span data-recipe-ingredient-name="">eggs</span></li>
  <li class="ingredient row" 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>
  <li class="ingredient row" data-recipe-ingredient="" data-origin="authored" data-optional=""><span data-recipe-ingredient-quantity="">1 cup</span> <span data-recipe-ingredient-name="">blueberries</span> <span data-recipe-ingredient-optional="">(optional)</span></li>
  <li class="ingredient row" data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
</ul>

With anything but one element child, <Recipe.Ingredient> renders its own <li> with those children, or with the default content when they’re undefined, null, true, or false. In development, the first <Recipe.Ingredient> to do this logs a development warning.

IngredientQuantity

TSX
'use client'

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

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe} defaultSystem="metric">
      <Recipe.IngredientList>
        {(item) => (
          <Recipe.Ingredient item={item} className="ingredient">
            <Recipe.IngredientQuantity className="quantity">
              {(quantity) => (
                <>
                  {item.origin === 'converted' && (
                    <span className="approx">≈ </span>
                  )}
                  {quantity}
                </>
              )}
            </Recipe.IngredientQuantity>
            <Recipe.IngredientName />
          </Recipe.Ingredient>
        )}
      </Recipe.IngredientList>
    </Recipe.Root>
  )
}

In metric, the recipe in the first example converts the buttermilk and the blueberries, so IngredientsCard marks their quantities as approximate:

HTML
<ul data-recipe-ingredient-list="">
  <li class="ingredient" data-recipe-ingredient="" data-origin="equivalent"><span class="quantity" data-recipe-ingredient-quantity="">190 g</span><span data-recipe-ingredient-name="">all-purpose flour</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="converted"><span class="quantity" data-recipe-ingredient-quantity=""><span class="approx">≈ </span>296 mL</span><span data-recipe-ingredient-name="">buttermilk</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">2</span><span data-recipe-ingredient-name="">eggs</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">3 tbsp</span><span data-recipe-ingredient-name="">butter</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="converted" data-optional=""><span class="quantity" data-recipe-ingredient-quantity=""><span class="approx">≈ </span>237 mL</span><span data-recipe-ingredient-name="">blueberries</span></li>
  <li class="ingredient" data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
</ul>

The ≈ marks a converted quantity, not a converted size. For '2 cans (15 oz each) tomatoes', the 2 cans are as written, so origin is authored, and in metric IngredientsCard shows 2 cans (425 g each) with no ≈.

<Recipe.IngredientQuantity> renders the quantity of the nearest <Recipe.Ingredient> in a <span> with data-recipe-ingredient-quantity, as formatQuantity formats it with Root’s locale and labels. For a can, a package, or another count unit with a mass or volume equivalent, the size follows in parentheses, as in formatIngredient’s text: 1 can (28 oz), or 2 cans (15 oz each). It renders nothing when the ingredient has no quantity. 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.

Name Type Description
asChild true Renders its only child instead of a <span>, with the quantity in it when the child’s children are undefined, null, true, or false. See Render a sub-part as your own element. Defaults to false. It needs exactly one element child. A value typed boolean, such as asChild={isLinked}, doesn’t type-check, so render the sub-part with and without asChild in separate branches.
children ((quantity: ReactNode) => ReactNode) | ReactElement | undefined A function that gets the quantity, with any size, and returns what to show in its place, such as the quantity after a ≈ in the example. With asChild, the one element to render.

Any other <span> prop passes to the <span>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML.

IngredientName

<Recipe.IngredientName> renders the name of the nearest <Recipe.Ingredient> in a <span> with data-recipe-ingredient-name. After a bare count that takes the plural, such as 2 or 1–2, it’s the ingredient’s plural, or its name when the plural is missing, empty, or only whitespace. Every ingredient has a name, so it always renders.

Name Type Description
asChild true Renders its only child instead of a <span>, such as a link, with the name in it when the child’s children are undefined, null, true, or false. See Render a sub-part as your own element. Defaults to false. It needs exactly one element child. A value typed boolean, such as asChild={isLinked}, doesn’t type-check, so render the sub-part with and without asChild in separate branches.
children ((name: ReactNode) => ReactNode) | ReactElement | undefined A function that gets the name and returns what to show in its place. With asChild, the one element to render.

Any other <span> prop passes to the <span>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML.

IngredientNote

<Recipe.IngredientNote> renders the note of the nearest <Recipe.Ingredient>, such as melted, in a <span> with data-recipe-ingredient-note. It renders nothing when the ingredient has no note.

Name Type Description
asChild true Renders its only child instead of a <span>, with the note in it when the child’s children are undefined, null, true, or false. See Render a sub-part as your own element. Defaults to false. It needs exactly one element child. A value typed boolean, such as asChild={isLinked}, doesn’t type-check, so render the sub-part with and without asChild in separate branches.
children ((note: ReactNode) => ReactNode) | ReactElement | undefined A function that gets the note and returns what to show in its place. With asChild, the one element to render.

Any other <span> prop passes to the <span>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML.

IngredientOptional

<Recipe.IngredientOptional> renders the optional label, (optional) by default, in a <span> with data-recipe-ingredient-optional when the nearest <Recipe.Ingredient> is optional. With an empty label, labels={labelPack({ optional: '' })}, it renders nothing, and the default content of <Recipe.Ingredient> drops the space before it. Given children, it still renders: a children function gets the empty label, and an asChild child renders as it is, so an icon alone can mark the ingredient as optional.

A note shows as written, so an ingredient written as { name: 'sugar', note: '(optional)', optional: true } shows “sugar, (optional) (optional)”. Set optional: true and leave “(optional)” out of the note. A line that parseIngredientLine parses already has it removed.

A non-empty label is text, so screen readers read it with the ingredient. An icon needs its own accessible name, so give an <svg> icon role="img" and an aria-label. Put the name on the icon, not the <span>: ARIA doesn’t allow a name on a plain <span>, so screen readers don’t reliably announce one.

Name Type Description
asChild true Renders its only child instead of a <span>, with the label in it when the child’s children are undefined, null, true, or false. See Render a sub-part as your own element. Defaults to false. It needs exactly one element child. A value typed boolean, such as asChild={isLinked}, doesn’t type-check, so render the sub-part with and without asChild in separate branches.
children ((label: ReactNode) => ReactNode) | ReactElement | undefined A function that gets the label and returns what to show in its place. With asChild, the one element to render.

Any other <span> prop passes to the <span>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML.

Render a sub-part as your own element

With asChild, a sub-part passes its data-recipe-* attribute, your other props, and its ref to its only child. The child’s own children replace the sub-part’s text, as they replace the content of <Recipe.Ingredient>. Use it to make a name a link:

TSX
'use client'

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

export function IngredientsCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.IngredientList>
        {(item) => (
          <Recipe.Ingredient item={item} className="ingredient">
            <Recipe.IngredientQuantity className="quantity" />
            <Recipe.IngredientName asChild>
              <a href={`/glossary/${item.id}`} />
            </Recipe.IngredientName>
          </Recipe.Ingredient>
        )}
      </Recipe.IngredientList>
    </Recipe.Root>
  )
}

For the recipe in the first example, IngredientsCard renders:

HTML
<ul data-recipe-ingredient-list="">
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">1 ½ cups</span><a href="/glossary/all-purpose-flour" data-recipe-ingredient-name="">all-purpose flour</a></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">1 ¼ cups</span><a href="/glossary/buttermilk" data-recipe-ingredient-name="">buttermilk</a></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">2</span><a href="/glossary/egg" data-recipe-ingredient-name="">eggs</a></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored"><span class="quantity" data-recipe-ingredient-quantity="">3 tbsp</span><a href="/glossary/butter" data-recipe-ingredient-name="">butter</a></li>
  <li class="ingredient" data-recipe-ingredient="" data-origin="authored" data-optional=""><span class="quantity" data-recipe-ingredient-quantity="">1 cup</span><a href="/glossary/blueberries" data-recipe-ingredient-name="">blueberries</a></li>
  <li class="ingredient" data-recipe-ingredient="" data-unquantified=""><a href="/glossary/maple-syrup" data-recipe-ingredient-name="">maple syrup</a></li>
</ul>

To put more than the name in the link, such as <a href={url}>Buy flour</a>, use a children function instead: {(name) => <a href={url}>Buy {name}</a>}. The link is then inside the <span>, which keeps data-recipe-ingredient-name.

Its props and ref merge with the child’s as asChild on the system toggle describes, along with what a function component needs on React 18. With anything but one element child, the sub-part renders its own <span> with a function’s result, or with those children, or with its text when they’re undefined, null, true, or false. In development, the first of each sub-part to do this logs a development warning.

Servings and measurement systems

Root resolves the recipe with resolveRecipe at its servings and in its measurement system, and each RecipeIngredientItem is one of the ResolvedIngredients it returns. When the servings or the system changes, such as through setServings or setSystem, the parts re-render with the new quantities. Scale a recipe explains how quantities scale.

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

export function DoubleBatch({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe} defaultServings={8}>
      <Recipe.IngredientList />
    </Recipe.Root>
  )
}

The recipe in the first example makes 4 servings, so at 8, DoubleBatch doubles every quantity:

HTML
<ul data-recipe-ingredient-list="">
  <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">3 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 ½ cups</span> <span data-recipe-ingredient-name="">buttermilk</span></li>
  <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">4</span> <span data-recipe-ingredient-name="">eggs</span></li>
  <li data-recipe-ingredient="" data-origin="authored"><span data-recipe-ingredient-quantity="">6 tbsp</span> <span data-recipe-ingredient-name="">butter</span>, <span data-recipe-ingredient-note="">melted</span></li>
  <li data-recipe-ingredient="" data-origin="authored" data-optional=""><span data-recipe-ingredient-quantity="">2 cups</span> <span data-recipe-ingredient-name="">blueberries</span> <span data-recipe-ingredient-optional="">(optional)</span></li>
  <li data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
</ul>
TSX
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function MetricIngredients({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe} defaultSystem="metric">
      <Recipe.IngredientList />
    </Recipe.Root>
  )
}

The recipe is written in US units. In metric, MetricIngredients shows the flour’s equivalent, 190 g, and converts the buttermilk and the blueberries to milliliters. The butter keeps 3 tbsp, since tbsp is native to both systems. data-origin tells them apart:

HTML
<ul data-recipe-ingredient-list="">
  <li data-recipe-ingredient="" data-origin="equivalent"><span data-recipe-ingredient-quantity="">190 g</span> <span data-recipe-ingredient-name="">all-purpose flour</span></li>
  <li data-recipe-ingredient="" data-origin="converted"><span data-recipe-ingredient-quantity="">296 mL</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>
  <li data-recipe-ingredient="" data-origin="converted" data-optional=""><span data-recipe-ingredient-quantity="">237 mL</span> <span data-recipe-ingredient-name="">blueberries</span> <span data-recipe-ingredient-optional="">(optional)</span></li>
  <li data-recipe-ingredient="" data-unquantified=""><span data-recipe-ingredient-name="">maple syrup</span></li>
</ul>

Labels

Two labels belong to ingredients: optional, which <Recipe.IngredientOptional> shows, and to, which follows the dash of a quantity range, as in “2–3 tbsp”, in text that’s hidden on screen. Set them with labels on <Recipe.Root> or <Recipe.Provider>.

An ingredient written as { name: 'lemon', plural: 'lemons', quantity: '1–2', note: 'zested', optional: true } renders:

HTML
<li data-recipe-ingredient="" data-origin="authored" data-optional=""><span data-recipe-ingredient-quantity=""><span style="white-space:nowrap">1<span data-recipe-range-separator="" aria-hidden="true">–</span><span style="position:absolute;border:0;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:pre;word-wrap:normal;user-select:none;-webkit-user-select:none"> to </span>2</span></span> <span data-recipe-ingredient-name="">lemons</span>, <span data-recipe-ingredient-note="">zested</span> <span data-recipe-ingredient-optional="">(optional)</span></li>

The dash has aria-hidden and data-recipe-range-separator, and the to label is in a <span> whose inline style hides it on screen, so it needs none of your CSS. The range is in a <span> with white-space: nowrap, so a line never ends after the dash. The page shows 1–2 lemons, zested (optional). In Chrome and Firefox, the to label takes the dash’s place in the accessibility tree, as in “1 to 2 lemons, zested (optional)”, but the text WebKitGTK gives screen readers keeps the dash, as Read ranges aloud shows.

Errors

<Recipe.Ingredients>, <Recipe.IngredientList>, and <Recipe.Ingredient> throw missing_parent with their own names when they aren’t inside <Recipe.Root>:

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

The four sub-parts throw it when they aren’t inside a <Recipe.Ingredient>:

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

<Recipe.Ingredient> throws invalid_argument when Root’s locale isn’t a language tag that Intl accepts, such as 'en_US', and so do <Recipe.Ingredients> and <Recipe.IngredientList> through the <Recipe.Ingredient> they render for each item by default. <Recipe.Ingredient> also throws it when an item you build isn’t { ingredient, quantity? }, has an ingredient whose name, plural, or note isn’t a string, has an amount, or shows a size after a count unit, that isn’t a finite number greater than 0 or a range of them, has a range whose min is greater than its max, or has a quantity with max set, as a yield has, and unknown_unit when the item’s unit isn’t a unit ID, unless it throws invalid_argument first, as it does for an amount of 0, or for an item from Root, 1e308 scaled past the largest number. For a recipe you build, <Recipe.Ingredients> and <Recipe.IngredientList> throw invalid_argument through the <Recipe.Ingredient> they render for each item by default when an ingredient’s name, plural, or note isn’t a string, at any servings and system, or when an ingredient’s quantity has an amount that isn’t a finite number greater than 0 or a range of them, or has max set, as a yield has. Not every such quantity gets that far, so some render instead: in 'metric', 0 cups of flour with a 250 g equivalent shows the equivalent, “250 g flour”. An amount can also become Infinity or 0 when it’s scaled or converted, as 1e308 cups does at 1,000 servings of a recipe for 4. They throw unknown_unit when an ingredient’s quantity has a unit that isn’t a unit ID, unless invalid_argument is thrown first, as for an amount of 0, or 1e308 scaled past the largest number, or an equivalent shows instead, as in resolveRecipe: the first native to Root’s system, else in 'metric' the first weight, as 1 bogus of flour with a 250 g equivalent shows “250 g flour” in 'metric'. An equivalent with such a unit never shows, so it never throws, and 2 cups of flour whose only equivalent has one show “473 mL flour” in 'metric'. Both lists also throw invalid_argument at any servings when the size shown after a count unit isn’t a finite number greater than 0 or a range of them, has a range whose min is greater than its max, or has max set. That size is the first mass or volume equivalent native to Root’s system, else the first, so they throw in both systems for 2 cans whose only size is { min: 3, max: 2 } oz, and only in 'metric' for 2 cans with sizes of 15 oz and 0 g. Neither <Recipe.Ingredient> nor the lists throw for a reversed size range, though, where the count is a range and the size shows one figure for each item, as 200–201 cans whose only size is { min: 101, max: 100 } oz show “½ oz each” in 'us'. In 'metric', 14 g each is more than 2% off, so they switch to the total and throw because the total’s range is still reversed.

For an item from a recipe you build, <Recipe.Ingredient>, <Recipe.Ingredients>, and <Recipe.IngredientList> also throw invalid_argument where the amount shown is a range whose min is greater than its max, or whose max is missing, null, or NaN. Flour as { amount: { min: 3, max: 2 }, unit: 'cup' } throws it under 'us' at 1×: the error names formatIngredient, and its message after the name is range minimum (3) must not be greater than the maximum (2). Under 'metric', the same flour with a 190 g equivalent shows “190 g flour”.

<Recipe.Ingredients> and <Recipe.IngredientList> call children for each section or ingredient. When children are undefined, null, true, or false, both parts render their defaults instead. Other children that aren’t a function, such as an element, '', or [], throw a TypeError. JavaScript throws it, not Recipe Book, so the message depends on the build and the engine. In Node, which runs V8, with the package’s unminified build, <Recipe.IngredientList> with an element throws TypeError: render is not a function. A production build renames render, and JavaScriptCore (Safari, Bun) adds the failing call after it. TypeScript rejects it:

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

export function Shopping({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.IngredientList>
        <li>Flour</li>
      </Recipe.IngredientList>
    </Recipe.Root>
  )
}
Text
error TS2322: Type 'Element' is not assignable to type '(item: ResolvedIngredient) => ReactNode'.

Pass a function, as in Render your own ingredients.

In a runtime without Intl, <Recipe.Ingredient>, <Recipe.Ingredients>, and <Recipe.IngredientList> don’t throw invalid_argument for any locale string, even 'en_US', and write the numbers in English.

Types

@recipe-book/react exports each part’s props type: RecipeIngredientsProps, RecipeIngredientListProps, RecipeIngredientProps, RecipeIngredientQuantityProps, RecipeIngredientNameProps, RecipeIngredientNoteProps, and RecipeIngredientOptionalProps. Use them to type a component that wraps a part:

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

export function IngredientsSection(props: Recipe.RecipeIngredientsProps) {
  return (
    <section aria-labelledby="ingredients">
      <h2 id="ingredients">Ingredients</h2>
      <Recipe.Ingredients {...props} />
    </section>
  )
}

The four sub-parts share one props type:

TypeScript
type RecipeIngredientQuantityProps = Omit<
  ComponentPropsWithoutRef<'span'>,
  'children' | 'dangerouslySetInnerHTML'
> &
  (
    | {
        asChild?: false | undefined
        children?: ((content: ReactNode) => ReactNode) | undefined
      }
    | { asChild: true; children: ReactElement }
  )
type RecipeIngredientNameProps = RecipeIngredientQuantityProps
type RecipeIngredientNoteProps = RecipeIngredientQuantityProps
type RecipeIngredientOptionalProps = RecipeIngredientQuantityProps

So type a wrapper that spreads its props into a sub-part with one of these, not with ComponentPropsWithoutRef<'span'>, whose children the sub-parts don’t take.

Don’t remove props from these four types with Omit, which flattens the union, so the spread no longer type-checks.

It also exports RecipeSection, the type of each section, RecipeIngredientItem, and RecipeHeadingLevel.

RecipeIngredientItem

TypeScript
type RecipeIngredientItem = ResolvedIngredient

One ingredient at Root’s servings and in its measurement system: a ResolvedIngredient from @recipe-book/react/core, with its id, the ingredient as written, the quantity to show, and the quantity’s origin. In metric, the buttermilk in the first example is this item:

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

export const buttermilk: Recipe.RecipeIngredientItem = {
  id: 'buttermilk',
  ingredient: {
    id: 'buttermilk',
    name: 'buttermilk',
    quantity: { amount: 1.25, unit: 'cup' },
    equivalents: [],
    optional: false,
  },
  quantity: { amount: 295.735295625, unit: 'ml' },
  origin: 'converted',
}

RecipeHeadingLevel

TypeScript
type RecipeHeadingLevel = 2 | 3 | 4 | 5 | 6

The heading levels that <Recipe.Ingredients> and <Recipe.Steps> take as headingLevel for section titles, and <Recipe.Notes> for note titles, without level 1, which belongs to the page’s title.

Named imports

To import these parts by name, import each one without the Recipe.: Ingredients, IngredientList, Ingredient, IngredientQuantity, IngredientName, IngredientNote, and IngredientOptional. If a name clashes with one of yours, alias it, as in import { Ingredients as RecipeIngredients } from '@recipe-book/react'.

Contents