Recipe Book0.6.0

4.3React reference

Servings

Reference for <Recipe.ServingsSelect> and <Recipe.ServingsInput>, which change a recipe's servings, and <Recipe.ServingsText> and <Recipe.YieldText>, which show them as text.

§ 4.322 min readView as Markdown

Two parts change the number of servings that <Recipe.Root> shows. <Recipe.ServingsSelect> offers a few numbers of servings in a <select>, and <Recipe.ServingsInput> takes a number typed in a number input. Two more show the recipe’s servings and yield at that number as text: <Recipe.ServingsText> and <Recipe.YieldText>. Each must be inside <Recipe.Root>.

The select and the input set servings with setServings, so every part and hook in the Root shows the recipe at the new number of servings. They follow Root’s rules for controlled state, the scaling base, and the servings window. On React 18, changing the servings with the select or the input 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. In development, React 18 also logs “useLayoutEffect does nothing on the server” once for each select and input in a server render where document is defined, such as a test that puts jsdom’s window and document on globalThis. A server render without document, a production build, and React 19 log nothing.

Pass your state itself as a controlled servings, not a value from useDeferredValue, and update it urgently in onServingsChange, not in a transition. Until the servings you pass catches up, the select goes back to it, and so does the input once it loses focus: after a reader picks 8 servings from 4, the select shows 4 again, picking 4 servings does nothing, and servings still change to 8 once the value catches up. To keep a slow part of the page from holding up the controls, pass the deferred value to that part instead. On React 19, to save servings in a transition anyway, pass the value from useOptimistic, as Controlled and uncontrolled state shows.

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

ServingsSelect

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}>
      <Recipe.ServingsSelect />
    </Recipe.Root>
  )
}

For the sample recipe, which has 4 servings, RecipeCard renders this HTML, indented here for reading:

HTML
<select autoComplete="off" aria-label="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>

Choosing 8 servings sets the Root’s servings to 8 and its scale to 2.

An option’s text is the number and the servingUnit label, as in “4 servings”. A recipe with only a yield shows the yield’s word instead, and a recipe with neither shows a multiplier, as Recipes without servings describes. Servings or a yield whose amount isn’t a finite number greater than 0, which only a recipe you build can have, count as none.

The default options depend on the recipe’s scaling base:

Recipe Scaling base Options
4 servings 4 2, 4, 8, and 12 servings
A yield of 24 cookies, and no servings 24 12, 24, 48, and 72 cookies
Neither servings nor a yield 1 1×, 2×, and 3×

The current servings are always an option, so a number set elsewhere still shows, unless it’s at a scale within 1e-9 of 1×. After a <Recipe.ServingsInput> in the same Root sets 5 servings, the select offers 2, 4, 5, 8, and 12 servings, with 5 selected. The options run from fewest to most, without duplicates.

Props

Name Type Description
options readonly number[] | undefined The numbers of servings to offer, such as [1, 1.5, 2] for half servings. A number outside the servings window is left out. Defaults to ½×, 1×, 2×, and 3× the recipe’s scaling base, each rounded to a whole number of at least 1.

Any other <select> prop, such as className or disabled, passes to the <select>, and a ref reaches it. Style it with className, or select the data-recipe-servings-select attribute, which it always sets. Style a recipe lists every data attribute that the parts set. The part sets the value and the options, so it doesn’t take value, defaultValue, multiple, children, or dangerouslySetInnerHTML. It also sets autoComplete="off", so Chrome and Firefox don’t restore an earlier choice when the page reloads, and an autoComplete you pass replaces it, with null (from JavaScript, or without strictNullChecks) leaving the attribute out. Safari restores one anyway when going back reloads the page. Whatever the browser restores, the select shows the Root’s servings once React has hydrated the page and the browser has shown it.

It’s a native <select>, so the browser provides its keyboard behavior. Each change event sets servings to the chosen number. An onChange you pass runs first, and calling event.preventDefault() in it keeps the servings as they are.

Option text

The select writes numbers as formatYield does, in Root’s locale, but with kitchen rounding only for a whole number of quarters, give or take float noise, such as 1.5, which reads “1 ½ servings”, as do the 1.5000000000000002 servings that setServings(0.1 * 3 * 5) sets. Any other number gets rounding: 'none', so it has up to 3 decimals: 2.1 servings set by a <Recipe.ServingsInput step="any"> read “2.1 servings”, not “2 servings” like the option for 2. A number that would read as 0 with 3 decimals gets more, so 0.0004 servings read “0.0004 servings”. Two numbers that round to the same 3 decimals can read the same: 12.0004 servings read “12 servings”, like the option for 12. With locale="de-DE", 0.2 servings read “0,2 servings”.

For a recipe with servings, the word is one or other from servingUnit, as its row in RecipeLabels describes. A no-break space (U+00A0) joins the number to its word, and a whole number to its fraction. getByRole('option', { name }) and jest-dom’s toHaveDisplayValue compare the text as it is, so a test needs U+00A0 there. Testing Library’s getByText and getByDisplayValue, and jest-dom’s toHaveTextContent, turn the option’s no-break space into a regular space before they compare, so they match a regular space and not U+00A0. user-event’s selectOptions matches an option’s value, which is the number of servings, or its markup, where the space is &nbsp;, so pass it the number, as in selectOptions(select, '8').

The option for the recipe’s scaling base reads its count as written, as resolveRecipe returns it at a scale within 1e-9 of 1, and servings that close to the base select that option rather than one of their own. For servings: '6-8', the options read “3 servings”, “6–8 servings”, “12 servings”, and “18 servings”.

A range gets kitchen rounding only when both ends are whole numbers of quarters, give or take float noise, and reads “6–8 servings”, with an en dash.

ServingsInput

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}>
      <Recipe.ServingsInput max={48} />
    </Recipe.Root>
  )
}

For the sample recipe, RecipeCard renders:

HTML
<input autoComplete="off" type="number" inputMode="numeric" aria-label="Servings" min="1" max="48" data-recipe-servings-input="" value="4"/>

<Recipe.ServingsInput> renders an <input type="number"> that shows the current servings. It’s a native number input, so the browser provides its keyboard behavior. When the browser steps the value, such as with the arrow keys, the new number sets servings like a typed one.

Name Type Description
min number | undefined The fewest servings the input accepts, set as its min attribute. The step grid starts from it. Defaults to 1.
max number | undefined The most servings the input accepts, set as its max attribute. Without it, the input has no max attribute and accepts numbers up to the top of the servings window.
step number | 'any' | undefined The step between values, set as its step attribute. A typed number must be on the step grid, and 'any' turns it off. Without it, the input has no step attribute, so the step is 1.

Any other <input> prop passes to the <input>, and a ref reaches it. Style it with className, or select the data-recipe-servings-input attribute, which it always sets. The part sets the type and the value, so it doesn’t take type, value, or defaultValue, and an input can’t have children or dangerouslySetInnerHTML. Like the select, it sets autoComplete="off" unless you pass autoComplete, with null (from JavaScript, or without strictNullChecks) leaving the attribute out, and whatever text the browser restores, it shows the Root’s servings once React has hydrated the page and the browser has shown it. Text the reader types before then gives way to the Root’s servings too. If the reader also submits before then, a form whose action is a function that runs in the browser still sends that text: React 19 replays the submit once it has hydrated the form, so the action gets the typed text while the input shows the Root’s servings. inputMode defaults to 'numeric' when min and step are whole numbers, as with the defaults of 1, or when min is whole and step counts as 1, and to 'decimal' otherwise, including with step="any". An onChange, onBlur, onCompositionStart, or onCompositionEnd you pass runs first. Calling event.preventDefault() in onChange drops the change, so the text and servings stay as they were, and calling it in onBlur keeps a draft on screen after the input loses focus. Calling it in onCompositionEnd leaves text the composition wrote before compositionend as a draft, though Firefox can write it in an input event after compositionend, which commits it. Calling it in onCompositionStart commits that composition as you type, as without an IME.

When it commits

The input commits as you type. Each change that leaves a number it accepts sets servings at once. It accepts a number that’s at least min, no more than max when you pass it, on the step grid, and inside the servings window.

With an input method editor (IME), such as for Japanese or Chinese, the input commits when the composition ends, so canceling one leaves servings as they were.

Anything else is a draft, which leaves servings as they are: an empty input, text that isn’t a number yet, 0, a negative number, a number off the step grid such as 1.5 with the default step, or a number out of range. The input doesn’t call setServings for a draft, so it logs no warning. When the input loses focus, it shows the current servings again and drops the draft. So does a reset of its form, such as the one a submit handler or a React 19 form action runs after you press Enter. The input hears the reset through a reset listener on window, after every reset handler on the form, the elements around it, and document, React’s onReset included, so any of those handlers can keep the draft by calling event.preventDefault() or event.stopPropagation(). A capture-phase handler on window can too, while a bubble-phase one may run before or after the input’s listener. A reset in a shadow root, or in an iframe the form is portaled into, never reaches that listener, so it keeps the draft as well.

While you’re typing a decimal, the input commits the number the text reads as so far, when it accepts that number. With step={0.5}, typing 1.5 sets 1 serving at 1, keeps 1 serving at 1., and sets 1.5 servings at 1.5. With the default step, 1.5 is a draft, so servings stay at 1, and the input shows 1 again when it loses focus.

With max={48}, as in the example, starting from 4 servings:

You The input shows Servings
Press Backspace Nothing 4
Type 1 1 1
Type 2 12 12
Type 0 120 12
Press Tab to move away 12 12

Enter does nothing of its own: the input has already set the number by the time you press it, and a draft stays as typed. In a form, Enter submits the form when the browser would from any text input: when the form’s first submit button isn’t disabled, or, in a form without a submit button, when no other <input> is one you type in, such as a second text field.

When servings change elsewhere, such as from a <Recipe.ServingsSelect> in the same Root, the input shows the new number. Text that already means the current number stays as typed, so 2.0 doesn’t become 2, even when controlled servings catch up with it later.

The step grid

The input checks a typed number against step the way the browser does: the grid starts at min and repeats every step.

  • With the defaults, min 1 and step 1, it accepts whole numbers, and 1.5 stays a draft.
  • With step={0.5}, it also accepts 1.5, 2.5, and so on.
  • With min={1.5} and the default step, it accepts 1.5, 2.5, 3.5, and so on, and 2 stays a draft.
  • With step="any", it accepts any number in range.

The check allows for floating-point error, so step={0.1} accepts 1.3. A step that isn’t a finite number above 0, such as Infinity, 0, or a negative number, counts as 1, as in the browser.

The browser also counts a number off the grid as a step mismatch, so the input matches :invalid while it shows one.

The input renders no text about which numbers it accepts. Use the keyboard shows how to say which with aria-describedby.

Decimal commas and pasted text

The browser reads the text as a number before the input gets it, so Root’s locale doesn’t change what a comma means. In Chrome, 1,5 reads as 1.5 when Chrome’s display language is German, and as 15 when it’s English, whatever the page’s lang. Firefox reads it in the page’s lang, so 1,5 reads as 1.5 on a page with lang="de" and is a draft on a page with lang="en". Both browsers read 1.5 as 1.5.

Chrome also drops the characters a number can’t hold from pasted text, so pasting 1 1/2 sets 112 servings, and pasting 1½ sets 1. With max={48}, as in the example, 112 is out of range, so it’s a draft. Firefox keeps pasted text as it is, so both stay drafts.

To offer a few fixed numbers instead, use a ServingsSelect: readers pick a number, so the browser has no text to read.

Accessible name

The select and the input set the servings label as aria-label. To name them another way:

  • Pass labels to <Recipe.Root> or a <Recipe.Provider> to rename every servings control inside it.
  • Pass aria-label to rename one control.
  • Pass aria-labelledby to name a control by another element. It outranks aria-label when that element has text. One that names no element with text, such as an id that isn’t on the page, leaves the aria-label as the name.
  • Pass aria-label="" to name a control with a <label>. The part then renders no aria-label, which would outrank the <label>.
TSX
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function ServingsField({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <label htmlFor="servings">Serves</label>
      <Recipe.ServingsInput id="servings" aria-label="" />
    </Recipe.Root>
  )
}
HTML
<label for="servings">Serves</label><input autoComplete="off" id="servings" type="number" inputMode="numeric" min="1" data-recipe-servings-input="" value="4"/>

Screen readers announce the input as “Serves”.

ServingsText

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} defaultServings={8}>
      <h2>
        Ingredients for <Recipe.ServingsText />
      </h2>
    </Recipe.Root>
  )
}

For the sample recipe, RecipeCard renders:

HTML
<h2>Ingredients for <span data-recipe-servings-text="">8 servings</span></h2>

<Recipe.ServingsText> renders the recipe’s servings at the Root’s servings, scaledServings. It writes them as the select’s options do: in Root’s locale, with the servingUnit label, and rounded as Option text describes.

It renders nothing for a recipe without servings, including one with only a yield, whose servings count in the yield’s unit. Show that recipe’s yield with <Recipe.YieldText>.

It’s text, so the server renders it. It prints as the page shows it. A range has a plain en dash, without the hidden to label that follows the dash in an ingredient quantity. The range is in a <span> with white-space: nowrap, so a line never ends after the dash. An asChild child gets the text as a plain string, with no <span>.

Name Type Description
asChild true Renders its only child instead of a <span>, such as an <li>, with the text in it when the child’s children are undefined, null, true, or false. It passes its data-recipe-servings-text attribute, your other props, and its ref to the child. Defaults to false. It needs exactly one element child.
children ReactElement | undefined With asChild, the one element to render.

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

With asChild, its props and ref merge with the child’s as asChild on the system toggle describes. With anything but one element child, it renders its own <span> with those children, or with its text when they’re undefined, null, true, or false. In development, the first <Recipe.ServingsText> to do this logs a development warning.

YieldText

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

export function CookieBatch({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe} defaultServings={48}>
      <p>
        Makes <Recipe.YieldText />
      </p>
    </Recipe.Root>
  )
}

For a recipe with a yield of 24 cookies and no servings, CookieBatch renders:

HTML
<p>Makes <span data-recipe-yield-text="">48 cookies</span></p>

<Recipe.YieldText> renders the recipe’s yield at the Root’s servings, scaledYield. It writes it as the select’s options do for a recipe with only a yield: in the yield’s own unit and plural, in Root’s locale, and rounded as Option text describes.

For a recipe with servings and a yield, the yield scales with the servings. For 4 servings that make 12–16 rolls, 8 servings make “24–32 rolls”. The reader chose neither end of that yield, so an end that isn’t a whole number of quarters, give or take float noise, rounds to a whole number: for 3 servings that make 10 rolls, 2 servings make “7 rolls”, and for 2 servings that make 2–3 rolls, 3 servings make “3–4 ½ rolls”. Each end rounds on its own, and the lower one comes first, so for 2 servings that make 5.2–5.5 rolls, 1 serving makes “2 ¾–3 rolls”. An end that would round to 0 keeps its decimals, so for 3 servings that make 1 loaf, 1 serving makes “0.333 loaves”, not “0 loaves”. At the recipe’s own servings, and at any scale within 1e-9 of 1, a count reads as written, so for 4 servings that make 2.1 loaves, 4 servings make “2.1 loaves”, not “2 loaves”. A yield in a mass or volume unit, such as '1 L' or '2 cups', doesn’t round to a whole number. It reads as formatQuantity writes the quantity, in the unit’s short label, so for 3 servings that make 1 L, 5 servings make “1.67 L”. That’s so at the recipe’s own servings too, so the yield reads the same way at every number: for 4 servings that make 1 quart, 4 servings make “1 qt”, and 8 make “2 qt”.

For a recipe with only a yield, the Root’s servings count in its unit, so at a scale within 1e-9 of 1 it reads as the recipe does, and at any other scale it’s that number, as <Recipe.ServingsText> is.

It renders nothing for a recipe without a yield. Otherwise it works as <Recipe.ServingsText> does, with the same props.

Show the servings, the yield, or both

With asChild, each text part can be an item in a list that holds only what the recipe has:

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

export function RecipeFacts({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <ul className="recipe-facts">
        <Recipe.ServingsText asChild>
          <li />
        </Recipe.ServingsText>
        <Recipe.YieldText asChild>
          <li />
        </Recipe.YieldText>
      </ul>
    </Recipe.Root>
  )
}

For the sample recipe, which has servings but no yield, RecipeFacts renders:

HTML
<ul class="recipe-facts"><li data-recipe-servings-text="">4 servings</li></ul>

Recipes without servings

When a recipe has a yield but no servings, servings count in the yield’s unit, as Root’s scaling base explains, so a <Recipe.ServingsInput> takes a number in the yield’s unit, such as cookies.

The controls are still named “Servings”, so name them for what they count, with a pack from labelPack, made 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 cookies = labelPack({ servings: 'Cookies' })

export function CookieCount({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe} labels={cookies}>
      <Recipe.ServingsSelect />
    </Recipe.Root>
  )
}

For a recipe with a yield of 24 cookies and no servings, CookieCount renders:

HTML
<select autoComplete="off" aria-label="Cookies" data-recipe-servings-select=""><option value="12">12 cookies</option><option value="24" selected="">24 cookies</option><option value="48">48 cookies</option><option value="72">72 cookies</option></select>

A yield written as text gets a plural from its last word before a comma or parentheses, so for yield: '1 sheet cake', the select offers “1 sheet cake”, “2 sheet cakes”, and “3 sheet cakes”, and at 2, <Recipe.YieldText> reads “2 sheet cakes”. The word before “of” or a plural container at the start is counted instead, as in '2 loaves banana bread', and YieldInput has every rule. A word with no other form, such as '2 dozen', stays as written at every number. Write the yield as an object, such as { amount: 1, unit: 'loaf', plural: 'loaves' }, to choose the words yourself. A plural that’s empty or only whitespace, which only a recipe you build can have, reads as none, so the yield keeps its unit at every number, as in “2 loaf”.

A recipe with neither servings nor a yield counts servings from 1, so they’re a multiplier, and 2× doubles the recipe. The select writes each number as in Option text, such as “½×” and “2.1×”. The controls are still named “Servings”, so name them for the multiplier too: with labelPack({ servings: 'Scale' }) as labels on <Recipe.Root>, the select and the input are both named “Scale”. <Recipe.ServingsText> and <Recipe.YieldText> both render nothing for it, so show the multiplier with scale from useRecipe(), as Root’s example does.

To let a link carry the scaled recipe, such as /recipes/pancakes?servings=8, start the Root at the link’s servings. This Next.js App Router page parses the Next.js example’s app/recipe.ts, which Render a recipe in React shows. It awaits connection(), so Next.js renders it on each request, and the server renders the link’s servings:

app/recipes/pancakes/page.tsx
import { parseRecipe } from '@recipe-book/react/core'
import { connection } from 'next/server'
import { pancakes } from '../../recipe'
import { ShareableRecipe } from './shareable-recipe'

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

  return <ShareableRecipe recipe={result.data} />
}

The Client Component reads the servings from the URL with useSearchParams and readRecipeView, which keeps only a number that <Recipe.Root> accepts. It starts an uncontrolled Root at them, and writes each change back to the URL:

app/recipes/pancakes/shareable-recipe.tsx
'use client'

import { readRecipeView, type ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useSearchParams } from 'next/navigation'

export function ShareableRecipe({ recipe }: { recipe: ParsedRecipe }) {
  const searchParams = useSearchParams()
  const view = readRecipeView(recipe, { servings: searchParams.get('servings') })

  return (
    <Recipe.Root
      recipe={recipe}
      defaultServings={view.servings}
      onServingsChange={(servings) => {
        const params = new URLSearchParams(location.search)
        params.set('servings', String(servings))
        history.replaceState(null, '', `?${params}`)
      }}
    >
      <Recipe.ServingsInput />
      <Recipe.Ingredients />
    </Recipe.Root>
  )
}
  • The server renders the recipe at the link’s servings, so nothing changes once React hydrates the page.
  • A missing or invalid servings, such as ?servings=-3 or ?servings=twelve, is left out of the view, so the Root starts at the scaling base and logs no warning.
  • history.replaceState changes the URL without navigating or adding a history entry, so typing 12 into the input, which sets 1 and then 12, never reloads the page. It keeps the URL’s other search params.
  • The servings come from useSearchParams, not from the page: on Back or Forward, Next.js renders the page from its router cache with the props it first had, while useSearchParams follows each history.replaceState. So after the reader leaves and comes back, the Root starts at the servings in the URL.
  • An uncontrolled Root reads defaultServings only when it mounts or the recipe’s id changes. A <Link> to the same page with other servings keeps the servings the reader has.

If your next.config.ts sets cacheComponents: true, add a loading state next to the page, as Render a recipe in React does. Next.js then keeps the last few pages the reader left mounted, so a <Link> back to this one from another page keeps the reader’s servings too. The address bar then shows that link’s servings, such as ?servings=8, or none for a link to /recipes/pancakes, rather than the Root’s, until the reader changes the servings again. To share the measurement system as well, pass the URL’s system to readRecipeView, which keeps only 'metric' or 'us'. Remember the reader’s choice keeps it in a cookie instead.

In Astro, read the servings in the frontmatter of a page that sets export const prerender = false, with an adapter installed. Pass Astro.url.searchParams.get('servings') to readRecipeView, and pass the view’s servings to an island like ShareableRecipe that takes them as a prop instead of calling useSearchParams. If the island reuses ShareableRecipe’s onServingsChange, pass history.state to history.replaceState instead of null, or Back to the page under Astro’s <ClientRouter /> changes the URL but leaves the previous page on screen. A static page ignores a link’s servings, and Astro doesn’t warn: it renders once, when astro build runs, and its Astro.url.searchParams is empty in development too.

In React Router, a component that reuses onServingsChange should pass history.state too, or <ScrollRestoration> can restore the top of the page on Back, not where the reader was. Even with history.state, history.replaceState leaves React Router’s own location behind, so useSearchParams misses the new servings, and a <Form> with no action posts to the URL from before the servings changed and puts that URL back in the address bar. In React Router 7.15 or later, setSearchParams with { replace: true, preventScrollReset: true, defaultShouldRevalidate: false } keeps them, without moving the page or rerunning loaders.

In a form

The select and the input take a name, so a form sends what they show. The select sends the number of its chosen option, such as 8. The input sends its text, which can be a draft: after you clear it and press Enter, the form sends an empty servings while the Root’s servings stay as they were. Without noValidate, a draft out of range or off the step grid fails the browser’s validation, so Enter doesn’t submit the form, and with noValidate the form sends that draft too. To send the Root’s servings whatever the input shows, render <input type="hidden" name="servings" value={Recipe.useRecipe().servings} /> in a component inside the Root.

A form reset, such as a reset button’s or the one React 19 runs after a form’s action, doesn’t change servings, and the select keeps showing the Root’s servings.

Errors

Each part throws missing_parent when it isn’t inside <Recipe.Root>:

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

<Recipe.ServingsInput>, <Recipe.ServingsText>, and <Recipe.YieldText> throw the same error with their own names.

<Recipe.ServingsSelect> throws invalid_argument when Root’s locale isn’t a language tag that Intl accepts, such as 'en_US'. So do <Recipe.ServingsText> for a recipe with servings and <Recipe.YieldText> for a recipe with a yield, even when an asChild child’s own children replace their text. For a recipe you build, <Recipe.ServingsText> also throws it at every servings for servings whose amount isn’t a finite number greater than 0, and <Recipe.YieldText> does the same for such a yield when the servings amount is valid, and otherwise only when the servings set a scale within 1e-9 of 1, as the recipe’s own servings do. <Recipe.ServingsText> throws it at every servings for servings whose amount is valid and whose max isn’t a finite number greater than it, so servings of 4–4 throw at 8 as they do at 4, and <Recipe.YieldText> does the same for such a yield. The exception is a max of Infinity on servings, or on the yield of a recipe that has no servings with a valid amount: it throws only at a scale within 1e-9 of 1. <Recipe.YieldText> reads a max equal to its amount as that amount for a yield that scales with the servings, so for 4 servings, 1–1 L reads “1 L” at 4 and “2 L” at 8, and 2–1 L throws at both, as does 1 L with a max of Infinity. Otherwise, at a scale more than 1e-9 from 1, they read servings as exactly the Root’s servings, and <Recipe.YieldText> reads a yield that way too when the recipe has no servings with a valid amount, whatever the yield’s own amount. <Recipe.YieldText> also throws it when the Root’s servings scale the yield’s amount or max past the largest number, such as an amount of 1e308 at 2×. <Recipe.ServingsSelect> also throws it for a recipe you build that has servings, or only a yield, whose max isn’t a finite number greater than its amount, Infinity included, when it shows the option for that amount, as it always does at a scale within 1e-9 of 1. parseRecipe never returns such a recipe.

In a runtime without Intl, <Recipe.ServingsSelect>, <Recipe.ServingsText>, and <Recipe.YieldText> don’t throw for any locale string, even 'en_US', and write the numbers in English.

Types

@recipe-book/react exports each part’s props type: RecipeServingsSelectProps, RecipeServingsInputProps, RecipeServingsTextProps, and RecipeYieldTextProps. Use them to type a component that wraps a part:

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

export function Servings(props: Recipe.RecipeServingsSelectProps) {
  return (
    <div className="servings">
      <Recipe.ServingsSelect {...props} />
    </div>
  )
}

The two text parts share one props type:

TypeScript
type RecipeServingsTextProps = Omit<
  ComponentPropsWithoutRef<'span'>,
  'children' | 'dangerouslySetInnerHTML'
> &
  (
    | { asChild?: false | undefined; children?: undefined }
    | { asChild: true; children: ReactElement }
  )
type RecipeYieldTextProps = RecipeServingsTextProps

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

Named imports

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

Contents