# Recipe Book

> Building blocks for recipe sites: scale servings, convert between metric and US units, and render recipes with React components that ship no CSS.

Source: https://recipe-book.siraj.page/

**Recipe pages where readers pick the servings and the units.**

Recipe Book is a TypeScript library for recipe sites. Write ingredients the way a recipe does, such as 1 ½ cups of flour, and it scales them with kitchen rounding, converts each one between US and metric, and converts the temperatures, weights and volumes in your steps to match. Its React parts ship no CSS and render plain HTML for you to style.

npm
```sh title="npm"
npm i @recipe-book/react
```

pnpm
```sh title="pnpm"
pnpm add @recipe-book/react
```

Yarn
```sh title="Yarn"
yarn add @recipe-book/react
```

Bun
```sh title="Bun"
bun add @recipe-book/react
```

An app without React installs `@recipe-book/core` instead.

[Read the quickstart](https://recipe-book.siraj.page/quickstart.md)

[Open the playground](https://recipe-book.siraj.page/playground/)

**Maple granola**

Servings: 4

Measurement system: US

- 2 cups rolled oats
- ½ cup chopped almonds
- ¼ cup maple syrup
- 2 tbsp olive oil
- ½ tsp salt

1. Toss everything together, spread it on a sheet pan, and bake at 325 °F for 25 minutes, stirring once. Serve with ½ cup of milk per bowl.

[Try the live demo](https://recipe-book.siraj.page/#try-it)

Live: A recipe as you write it, and as the React parts render it. Change the servings or the units.

recipe.ts
```ts title="recipe.ts"
import type { RecipeInput } from '@recipe-book/react/core'

export const pancakes = {
  name: 'Buttermilk pancakes',
  servings: 4,
  times: { prep: 10, cook: 15 },
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
    { name: 'sugar', quantity: '2 tbsp', equivalents: ['25 g'] },
    { name: 'baking powder', quantity: '2 tsp' },
    { name: 'buttermilk', quantity: '1 ¼ cups' },
    { name: 'egg', plural: 'eggs', quantity: 2 },
    {
      name: 'butter',
      quantity: '3 tbsp',
      note: 'melted',
      equivalents: ['42 g'],
    },
    { name: 'maple syrup', note: 'to serve' },
  ],
  steps: [
    'Whisk the dry ingredients in a large bowl.',
    'Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.',
    'Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.',
  ],
} satisfies RecipeInput
```

**Buttermilk pancakes**

Servings: 4

Measurement system: US

**Ingredients**

- 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

**Steps**

1. Whisk the dry ingredients in a large bowl.
2. Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.
3. Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.

[Try the live demo](https://recipe-book.siraj.page/)

## What it does

**Scaling with kitchen rounding**

Ask for 8 servings of a recipe for 4, and 1 ½ cups of flour becomes 3 cups, or 6 tbsp for 1 serving. US amounts, metric cups, and Australian tablespoons round to the nearest ⅛ or ⅓ and read as fractions, or, below ⅛, as a decimal such as 0.1 tsp. Other metric amounts round to sensible decimals.

[Scale a recipe](https://recipe-book.siraj.page/guides/scale-a-recipe.md)

**Metric and US, per ingredient**

Give flour a weight, `equivalents: ['190 g']`, and metric readers see 190 g, scaled with the recipe, instead of a guess from a density table. Volumes and weights without one convert within their kind, so 1 ¼ cups of buttermilk reads 296 mL.

[Convert units](https://recipe-book.siraj.page/guides/convert-units.md)

**Oven temperatures in step text**

[`<Recipe.Steps>`](https://recipe-book.siraj.page/reference/react/steps.md#steps) finds the temperatures in each step and shows them in the reader's system, so “Preheat oven to 190°C (375°F).” reads “Preheat oven to 375 °F.” for US readers. [`<Recipe.StepText>`](https://recipe-book.siraj.page/reference/react/steps.md#steptext) does the same in steps you render yourself, and in core, [`segmentStepText`](https://recipe-book.siraj.page/reference/core/units.md#segmentsteptext) finds them for any renderer.

[Render your own steps](https://recipe-book.siraj.page/guides/render-a-recipe-in-react.md#render-your-own-steps)

**Accessible React parts that ship no CSS**

The parts ship no CSS and render plain HTML with no class names: a `<select>` named Servings, a radio group named Measurement system, and lists for the ingredients and steps. Style them with `className` or the `data-recipe-*` attribute on each part that renders an element.

[Style a recipe](https://recipe-book.siraj.page/guides/style-a-recipe.md) and [make it accessible](https://recipe-book.siraj.page/guides/make-a-recipe-accessible.md)

**schema.org JSON-LD in and out**

Import a recipe from another site: [`findRecipeJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#findrecipejsonld) finds the Recipe JSON-LD in its HTML, and [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) reads it into a recipe you can scale and convert. [`<Recipe.JsonLd>`](https://recipe-book.siraj.page/reference/react/json-ld.md) and [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) write yours for search engines' recipe results.

[Import recipes](https://recipe-book.siraj.page/guides/import-recipes.md)

**Two packages, no other dependencies**

`@recipe-book/core` parses, scales, converts, and formats recipes without React. `@recipe-book/react` adds the parts and hooks, depends only on core, and takes React as a peer. The schema.org functions are a separate import, `@recipe-book/core/schema-org`.

[Compare the packages](https://recipe-book.siraj.page/introduction.md#packages)

## The pancake card's source

The pancake card beside `recipe.ts` is Recipe Book's React parts, styled with plain CSS on the `data-recipe-*` attribute each part renders:

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

import './recipe-card.css'

export function RecipeCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <div className="recipe-card">
        <header>
          <h2>{recipe.name}</h2>
          <Recipe.ServingsSelect />
          <Recipe.SystemToggle />
        </header>
        <h3>Ingredients</h3>
        <Recipe.Ingredients headingLevel={4} />
        <h3>Steps</h3>
        <Recipe.Steps headingLevel={4} />
      </div>
    </Recipe.Root>
  )
}
```

recipe-card.css
```css title="recipe-card.css"
.recipe-card {
  --card-paper: var(--paper-raised);
  --card-ink: var(--ink);
  --card-soft: var(--ink-soft);
  --card-accent: var(--accent);
  padding: 1.25rem 1.25rem 0.5rem;
  background: var(--card-paper);
  color: var(--card-ink);
}

.recipe-card header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.5rem 0.75rem;
  padding-bottom: 0.9rem;
  border-bottom: 1px solid var(--card-rule);
}
.recipe-card h2 {
  flex: 1 0 100%;
  margin: 0;
  font-size: 1.5em;
  line-height: 1.1;
}
.recipe-card h3 {
  margin: 1.1rem 0 0.4rem;
  color: var(--card-accent);
  font-size: 0.8em;
  letter-spacing: 0.1em;
  text-transform: uppercase;
}

/* Each browser puts its arrow a different distance from the edge, so this
   draws a chevron instead, as far in from the edge as the text. */
.recipe-card [data-recipe-servings-select] {
  -webkit-appearance: none;
  appearance: none;
  padding: 0.3rem calc(1.25rem + 0.625em) 0.3rem 0.625rem;
  border: 1px solid var(--card-soft);
  border-radius: 0;
  background-color: var(--card-paper);
  background-image:
    linear-gradient(
      to top right,
      transparent calc(50% - 1px),
      var(--card-soft) calc(50% - 0.5px) calc(50% + 0.5px),
      transparent calc(50% + 1px)
    ),
    linear-gradient(
      to top left,
      transparent calc(50% - 1px),
      var(--card-soft) calc(50% - 0.5px) calc(50% + 0.5px),
      transparent calc(50% + 1px)
    );
  background-position:
    right calc(0.625rem + 0.3125em - 1px) center,
    right 0.625rem center;
  background-size: 0.3125em 0.3125em;
  background-repeat: no-repeat;
  color: var(--card-ink);
  font: inherit;
}
.recipe-card [data-recipe-system-toggle] {
  display: flex;
  border: 1px solid var(--card-soft);
}
.recipe-card [data-recipe-system-option] {
  padding: 0.3rem 0.65rem;
  border: 0;
  background: none;
  color: var(--card-ink);
  font: inherit;
  cursor: pointer;
}
.recipe-card [data-recipe-servings-select]:hover {
  border-color: var(--card-accent);
}
.recipe-card [data-recipe-system-option]:not([data-state='checked']):hover {
  background: var(--card-accent);
  color: var(--card-paper);
}
.recipe-card [data-recipe-system-option]:not([data-state='checked']):active {
  background: var(--card-ink);
  color: var(--card-paper);
}
.recipe-card [data-recipe-system-option][data-state='checked'] {
  background: var(--ribbon);
  color: var(--on-ribbon);
}
@media (forced-colors: active) {
  /* Chromium and Firefox drop the drawn chevron here, so the native arrow
     comes back. */
  .recipe-card [data-recipe-servings-select] {
    appearance: auto;
    padding-right: 0.625rem;
    background-image: none;
  }
  /* forced-color-adjust: none keeps Chromium's backplate from hiding the
     label, and the focus ring then needs CanvasText. */
  .recipe-card [data-recipe-system-option][data-state='checked'] {
    forced-color-adjust: none;
    background-color: Highlight;
    color: HighlightText;
    outline-color: CanvasText;
  }
}

.recipe-card :is([data-recipe-ingredient-list], [data-recipe-step-list]) {
  margin: 0;
  padding: 0;
}
.recipe-card [data-recipe-ingredient] {
  padding: 0.3rem 0 0.3rem 6em;
  border-bottom: 1px dotted var(--card-rule);
  list-style: none;
}
.recipe-card [data-recipe-ingredient-quantity] {
  /* Inline, not positioned: the space or no-break space after the quantity
     then lands in the same place whether or not it has a unit. */
  display: inline-block;
  width: 5.75em;
  margin-left: -6em;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}
.recipe-card [data-recipe-ingredient-note] {
  color: var(--card-soft);
}
.recipe-card [data-recipe-step] {
  margin: 0 0 0.5rem 1.25rem;
  padding-left: 0.25rem;
}
.recipe-card [data-recipe-step]::marker {
  color: var(--card-accent);
  font-weight: 600;
}
.recipe-card [data-recipe-temperature] {
  font-weight: 600;
}
```

Its recipe is the `recipe.ts` beside it, the [Quickstart](https://recipe-book.siraj.page/quickstart.md)'s, parsed with [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe):

sample-recipe.ts
```ts title="sample-recipe.ts"
import { parseRecipe } from '@recipe-book/core'

import { pancakes } from '../../../examples/vite-spa/src/recipe'

const result = parseRecipe(pancakes)

if (!result.success) {
  throw result.error
}
if (result.warnings.length > 0) {
  throw new Error(
    `recipe.ts: ${result.warnings.map((issue) => issue.message).join(' ')}`,
  )
}

export const sampleRecipe = result.data
```

This site also depends on `@recipe-book/core`, so `recipe-card.tsx` and `sample-recipe.ts` import from it. An app that depends only on `@recipe-book/react` imports `ParsedRecipe` and `parseRecipe` from `@recipe-book/react/core` instead, because with pnpm or Yarn Plug'n'Play it can't import a package that isn't in its `package.json`.

Paste your own recipe input, or a recipe page's HTML source, into the [playground](https://recipe-book.siraj.page/playground/) to try it.

## Next steps

- [Quickstart](https://recipe-book.siraj.page/quickstart.md): Install the React package and render your first recipe, with servings and a metric and US toggle.

- [Guides](https://recipe-book.siraj.page/guides/author-recipes.md): Step-by-step guides, from authoring and scaling recipes to rendering, styling, and importing them. Starts with Author recipes.

- [Error codes](https://recipe-book.siraj.page/errors.md): What each error code and development warning means, and how to fix it.

- [Core reference](https://recipe-book.siraj.page/reference/core/parsing.md): Every function and type that core exports, starting with parseRecipe.

- [React reference](https://recipe-book.siraj.page/reference/react/root.md): Every part and hook that the React package exports, starting with Recipe.Root.
