Recipe Book0.6.0

4.13React reference

Nutrition

Reference for <Recipe.Nutrition>, which renders a recipe's nutrition facts per serving as a description list.

§ 4.135 min readView as Markdown

<Recipe.Nutrition> renders the recipe’s nutrition facts for one serving, such as its calories, as a description list, with each nutrient’s label as the term and its quantity as the description. It must be inside <Recipe.Root>.

Nutrition

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

const result = parseRecipe({
  name: 'Sandwich bread',
  ingredients: [{ name: 'bread flour', quantity: '500 g' }],
  steps: ['Knead the dough until smooth.'],
  nutrition: {
    servingSize: '1 slice',
    calories: 180.6,
    fat: 2.25,
    carbohydrates: 33.33,
    fiber: 1.26,
    protein: 6,
    sodium: 310,
  },
})
if (!result.success) throw result.error
const recipe = result.data

export function BreadNutrition() {
  return (
    <Recipe.Root recipe={recipe}>
      <h2>Nutrition per serving</h2>
      <Recipe.Nutrition />
    </Recipe.Root>
  )
}

BreadNutrition renders this HTML, indented here for reading:

HTML
<h2>Nutrition per serving</h2>
<dl data-recipe-nutrition="">
  <div data-recipe-nutrient="servingSize"><dt>Serving size</dt><dd>1 slice</dd></div>
  <div data-recipe-nutrient="calories"><dt>Calories</dt><dd>181 kcal</dd></div>
  <div data-recipe-nutrient="fat"><dt>Fat</dt><dd>2.3 g</dd></div>
  <div data-recipe-nutrient="carbohydrates"><dt>Carbohydrates</dt><dd>33.3 g</dd></div>
  <div data-recipe-nutrient="fiber"><dt>Fiber</dt><dd>1.3 g</dd></div>
  <div data-recipe-nutrient="protein"><dt>Protein</dt><dd>6 g</dd></div>
  <div data-recipe-nutrient="sodium"><dt>Sodium</dt><dd>310 mg</dd></div>
</dl>

The serving size comes first, as written, unless it’s '', then each nutrient the recipe gives, in the order of core’s Nutrition type: calories, fat, saturated fat, trans fat, unsaturated fat, carbohydrates, sugar, fiber, protein, sodium, and cholesterol. A nutrient the recipe doesn’t give has no row, and one with a value of 0 still has one, such as “0 kcal”, “0 g”, or “0 mg”. <Recipe.Nutrition> renders nothing when the recipe has no nutrition facts. The part writes no heading, so write your own, and let the serving size say what a serving is. Nutrition is per serving, so it doesn’t scale with servings.

Calories show in kcal, and sodium and cholesterol in mg, rounded to whole numbers. The other nutrients show in g, rounded to one decimal place, so 12.0 shows as “12 g”. A negative value that rounds to 0, such as -0.04 g, which only a recipe you build can have, shows as 0, not -0. The rounding is for display only: it doesn’t follow the FDA’s rules for nutrition labels, which round each nutrient in its own steps. The unit symbols are the same in every locale, joined to the number by a no-break space, and the digits and decimal mark follow Root’s locale, so 'de-DE' shows “2,3 g”.

The terms come from Root’s labels: servingSize, and one for each nutrient, named as its key in Nutrition, such as saturatedFat.

Name Type Description
asChild true Renders the list as its only child instead of a <dl>. See Render 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 list with and without asChild in separate branches.
children ((nutrient: RecipeNutrientItem) => ReactNode) | ReactElement | undefined Renders each row instead of the default: a <div data-recipe-nutrient> around a <dt> and a <dd>. See Render your own rows. With asChild, the one element to render.

Any other <dl> prop, such as className or aria-label, passes to the <dl>, and a ref reaches it. It renders its own content, so it doesn’t take dangerouslySetInnerHTML. Style it with className, or select its data-recipe-nutrition attribute, or each row’s data-recipe-nutrient, which is set to the row’s key, such as servingSize or fat.

Render your own rows

Pass a function as children from a Client Component, as with <Recipe.Steps>. It receives a RecipeNutrientItem for each row, and <Recipe.Nutrition> keys each result, so an element or fragment you return needs no key. Return null to leave a row out, such as to show only calories and protein:

TSX
'use client'

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

const shown = new Set(['calories', 'protein'])

export function NutritionSummary({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Nutrition>
        {(nutrient) =>
          shown.has(nutrient.id) ? (
            <div>
              <dt>{nutrient.label}</dt>
              <dd>{nutrient.text}</dd>
            </div>
          ) : null
        }
      </Recipe.Nutrition>
    </Recipe.Root>
  )
}

For the recipe in the first example, NutritionSummary renders:

HTML
<dl data-recipe-nutrition="">
  <div><dt>Calories</dt><dd>181 kcal</dd></div>
  <div><dt>Protein</dt><dd>6 g</dd></div>
</dl>

For a nutrient’s unrounded number, read recipe.nutrition[nutrient.id]. For the serving size, that’s the string as written.

Render your own element

With asChild, <Recipe.Nutrition> passes data-recipe-nutrition, your other props, and its ref to its only child. Use it for a component that must be the list itself, such as an animated motion.dl. 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 replace the rows. A child whose children are undefined, null, true, or false gets the default rows, but any other children replace them, even '', [], or an empty Fragment, which render nothing. Here, Facts stands in for a component like that:

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

function Facts(props: ComponentProps<'dl'>) {
  return <dl {...props} />
}

export function NutritionFacts({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.Nutrition asChild className="nutrition">
        <Facts className="facts" />
      </Recipe.Nutrition>
    </Recipe.Root>
  )
}

For a recipe whose only nutrition fact is 320 calories, NutritionFacts renders:

HTML
<dl class="nutrition facts" data-recipe-nutrition="">
  <div data-recipe-nutrient="calories"><dt>Calories</dt><dd>320 kcal</dd></div>
</dl>

The child should render a <dl>, so the rows stay in a description list. With anything but one element child, such as text, several children, a function, or a Fragment, <Recipe.Nutrition> renders its own <dl> with those children, or with the default rows when they’re undefined, null, true, or false. In development, the first <Recipe.Nutrition> to do this logs a development warning.

Errors

Throws missing_parent when it isn’t inside <Recipe.Root>:

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

Throws invalid_argument for a recipe with a nutrient when Root’s locale isn’t a language tag that Intl accepts, such as 'en_US':

Text
RecipeBookError: <Recipe.Nutrition>: locale must be a language tag that Intl accepts, such as "en-US", received "en_US".
See https://recipe-book.siraj.page/errors/invalid_argument/

The amounts are in English for en alone or with a region such as en-GB, and for a locale the runtime doesn’t support, as core’s formatters write them, so 'en-ZA' shows “2.3 g” where Intl writes “2,3 g”. In a runtime without Intl, <Recipe.Nutrition> writes English for every string locale, even 'en_US', and doesn’t throw. A locale that isn’t a string, null or undefined, such as ['de-DE'], throws invalid_argument for a recipe with a nutrient, with or without Intl.

Types

@recipe-book/react exports the props type as RecipeNutritionProps, to type a component that wraps the part:

TypeScript
type RecipeNutritionProps = Omit<
  ComponentPropsWithoutRef<'dl'>,
  'children' | 'dangerouslySetInnerHTML'
> &
  (
    | {
        asChild?: false | undefined
        children?: ((nutrient: RecipeNutrientItem) => ReactNode) | undefined
      }
    | { asChild: true; children: ReactElement }
  )

Don’t remove props from RecipeNutritionProps with Omit, which flattens the union, so <Recipe.Nutrition {...props}> no longer type-checks.

RecipeNutrientItem

TypeScript
type RecipeNutrientItem = {
  id: keyof Nutrition
  label: string
  text: string
}

One row, as <Recipe.Nutrition> passes it to children.

Name Type Description
id keyof Nutrition The row’s key in recipe.nutrition: 'servingSize', or a nutrient such as 'fat'.
label string The label for id, such as the fat label.
text string The serving size as written, or the rounded amount and its unit, such as “12.5 g”.

Named imports

To import <Recipe.Nutrition> by name, import Nutrition. If the name clashes with one of yours, alias it, as in import { Nutrition as RecipeNutrition } from '@recipe-book/react'.

Contents