# Boing docs: install and use spring-physics toasts

Install `react-boing`, render `<Toaster />` once, and call `toast.success('Saved')` from any event handler. That is the whole setup: no provider, no stylesheet import and no other dependencies.

## How do I install Boing?

Add the package with the package manager your project uses:

```bash
npm install react-boing
```

React 18 or newer is the only peer dependency, and the package has no runtime dependencies of its own. It ships ESM and CommonJS builds with type definitions. The toast stylesheet is added to the page by the `<Toaster />` component, so there is nothing to import from CSS.

## Set up the Toaster

Render `<Toaster />` a single time, near the root of your app. It draws the toasts and their live regions. Then import `toast` wherever something happens that the user should hear about:

```tsx
import { Toaster, toast } from 'react-boing';

export function App() {
  return (
    <>
      <button type="button" onClick={() => toast.success('Draft saved')}>
        Save draft
      </button>
      <Toaster />
    </>
  );
}
```

`toast` is a shared store, not a hook, so you can call it from event handlers, effects, data-fetching code or plain modules. The Toaster reads from that same store.

## Next.js App Router

The published files begin with a `"use client"` directive, so a server component such as the root layout can import and render the Toaster directly:

```tsx
import { Toaster } from 'react-boing';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Toaster position="bottom-right" />
      </body>
    </html>
  );
}
```

Toasts are shown in the browser, so call `toast` from client code: a component marked `'use client'`, usually inside an event handler.

```tsx
'use client';

import { toast } from 'react-boing';

export function InviteButton() {
  return (
    <button type="button" onClick={() => toast.info('Invite link copied')}>
      Copy invite link
    </button>
  );
}
```

The Toaster renders on the server without touching the DOM, so it is safe in static and streamed pages.

## Show a toast

There is one shortcut per type: `success`, `error`, `warning`, `info` and `loading`. Each takes a title and optional [options](https://boing.aayushbharti.in/docs/#options), and returns the toast id. `toast.show(type, title, options)` does the same with the type as a value.

```ts
import { toast } from 'react-boing';

toast.success('Changes published');
toast.error('Could not reach the server', { description: 'Check your connection and try again.' });
toast.show('warning', 'Storage almost full', { meta: '92%' });
```

### How long does a toast stay?

- Success, warning and info toasts close after 5 seconds.
- Error and loading toasts, and any toast with a button, stay until they are dismissed or updated.
- A `duration` option in milliseconds overrides both rules. `0` means "stay until dismissed".

### One toast at a time

Boing keeps one toast on screen. A new call while a toast is visible does not stack a second one: the visible toast changes shape and content to become the new one. Calling the same type with the same title and description again adds a `×2` counter and restarts the timer instead. To keep some toasts on screen side by side, see [held modes](https://boing.aayushbharti.in/docs/#held).

## Update a toast in place

Keep the id a call returns and pass it to `toast.update` with the fields to change. The toast morphs to the new type, text and size without leaving the screen.

```ts
const id = toast.loading('Exporting report…');

try {
  await exportReport();
  toast.update(id, { type: 'success', title: 'Report ready', description: 'Sent to your inbox.' });
} catch {
  toast.update(id, { type: 'error', title: 'Export failed' });
}
```

Changing the type also resets the timer to that type's usual length, so the success above closes on its own while an error would stay. Set a field to `null` to remove it, for example `{ description: null }`.

### Promises

`toast.promise` does the loading, success and error steps for you. The messages can be functions that receive the result or the error. It returns the promise you gave it, so rejections still reach your code.

```ts
await toast.promise(uploadAvatar(file), {
  loading: 'Uploading avatar…',
  success: (user) => `Looking good, ${user.name}`,
  error: 'Upload failed',
});
```

### Progress

A `progress` value from `0` to `1` draws a bar along the bottom edge. Progress updates are not read out by screen readers, so ticking it often stays quiet. Pass `progress: null` to remove the bar.

```ts
const id = toast.loading('Syncing photos…', { progress: 0 });

for (const [done, total] of syncSteps()) {
  toast.update(id, { progress: done / total });
}

toast.update(id, { type: 'success', title: 'Photos synced', progress: null });
```

> **Note:** Only the newest caller can update a toast. If a second call took the toast over, a late `update` from the first one is ignored, so a slow request cannot overwrite a newer message.

## Add an action or undo button

Give a toast an `action` (and optionally a `secondary` button). If `onClick` returns a patch, the toast morphs into it and the buttons go away. If it returns nothing, the toast closes.

```ts
toast.success('Card archived', {
  duration: 6000,
  action: {
    label: 'Undo',
    onClick: () => {
      restoreCard();
      return { type: 'info', title: 'Card restored' };
    },
  },
});
```

A toast with a button stays until it is handled. Give it a `duration`, as above, and a slim bar along the bottom counts down the time remaining. The secondary button sits before the main one.

## Toast options

The second argument of every `toast` shortcut. All fields are optional.

| Option | Type | What it does |
| --- | --- | --- |
| `description` | `string` | A second, smaller line under the title. |
| `duration` | `number` | Milliseconds before the toast closes. `0` keeps it until dismissed. |
| `action` | `{ label, onClick }` | The main button. `onClick` may return a patch to morph into. |
| `secondary` | `{ label, onClick }` | A quieter second button, placed before the action. |
| `progress` | `number` | A progress bar from `0` to `1`. |
| `meta` | `string` | Small text after the title, such as a time or a count. |
| `image` | `string` | URL of a round image shown in place of the icon, such as an avatar. |
| `className` | `string` | Extra class on this toast's `.boing` element. |
| `id` | `string` | Your own id, to update or dismiss the toast later. |

### Other methods

| Method | What it does |
| --- | --- |
| `toast.update(id, patch)` | Changes a toast in place. A patch takes `type`, `title` and any option; `null` removes a field. |
| `toast.promise(promise, messages)` | Loading, then success or error. Accepts a promise or a function that returns one. |
| `toast.dismiss(id?)` | Closes one toast, or every toast when called without an id. `{ immediate: true }` removes it at once, without shrinking back first. |
| `toast.pause(id?)` / `toast.resume(id?)` | Stops and restarts the timer of one toast or of all of them. |
| `toast.act(id, which?)` | Runs a toast's `'action'` (the default) or `'secondary'` button from code. |
| `toast.subscribe(fn)` / `toast.getState()` | Low-level access to the store, for example with `useSyncExternalStore`. |

## Toaster props and toast.configure

The `<Toaster />` takes four props. Leave one out to keep its default.

| Prop | Default | What it does |
| --- | --- | --- |
| `position` | `'top-center'` | `top-left`, `top-center`, `top-right`, `bottom-left`, `bottom-center` or `bottom-right`. |
| `theme` | `'system'` | `'light'`, `'dark'` or `'system'` to follow the visitor's setting. |
| `labels` | English | `{ region, dismiss }`: the name of the toast region and of the close button. |
| `nonce` | none | Nonce for the injected `<style>` element. See [CSP](https://boing.aayushbharti.in/docs/#csp). |

`toast.configure` sets the same things from code, plus behaviour that has no prop. It can be called at any time; new values apply to toasts shown afterwards.

```ts
toast.configure({
  position: 'bottom-left',
  theme: 'dark',
  held: 'list',
  sound: true,
  volume: 0.3,
  springs: { enter: { stiffness: 260, damping: 18 } },
});
```

| Key | Default | What it does |
| --- | --- | --- |
| `position`, `theme`, `labels` | as above | Same as the Toaster props. |
| `held` | `'replace'` | How sticky toasts share the screen. See [held modes](https://boing.aayushbharti.in/docs/#held). |
| `sound` | `false` | `true` plays the built-in chime; a function receives the toast type instead. See [sound](https://boing.aayushbharti.in/docs/#sound). |
| `volume` | `0.5` | Chime volume from `0` to `1`. |
| `springs` | see below | Stiffness and damping for `enter`, `morph` and `stack`. |
| `icons` | built in | Replacement icons per type: a list of SVG path strings on a 24 by 24 canvas, drawn as strokes. |

The springs default to `enter` 320/26, `morph` 340/27 and `stack` 400/36 (stiffness/damping). The same solver is exported as `springEasing({ stiffness, damping })`, which returns a CSS `linear()` easing and a duration in milliseconds for your own animations.

## Sticky toasts and held modes

A toast is sticky when it has no timer: errors, toasts with a button, and anything with `duration: 0`. The `held` setting decides what happens when a new toast arrives while a sticky one is on screen. Loading toasts never count as sticky here, since they are about to change anyway.

| Mode | What happens |
| --- | --- |
| `'replace'` (default) | The new toast takes over the visible one, sticky or not. Only one toast is ever on screen. |
| `'list'` | Sticky toasts keep their place, and quick toasts appear next to them in a list. A quick toast still morphs the previous quick one. |
| `'queue'` | While a sticky toast is open, new toasts wait in line and appear one by one, in order, after it is dismissed. |

```ts
toast.configure({ held: 'list' });

toast.error('Payment failed', { description: 'Your card was declined.' }); // stays
toast.success('Address saved'); // shows beside the error and closes on its own
```

In queue mode, `toast.update` on a waiting toast changes what will be shown when its turn comes.

## Content Security Policy

The Toaster adds one `<style data-toast>` element at the start of `<head>`. If your Content Security Policy limits inline styles with a nonce, pass the same nonce to the Toaster:

```tsx
<Toaster nonce={nonce} />
```

Icons carry their own width and height, so even if the stylesheet is blocked by a wrong nonce they stay small instead of filling the page.

## How do I style the toasts?

Set CSS variables on `.boing-viewport`. Because the built-in stylesheet is placed first in `<head>`, any of your own rules win without `!important`. Colours use `light-dark()`, so one value per theme is enough.

```css
.boing-viewport {
  --boing-bg: light-dark(#fffdf7, #16130f);
  --boing-fg: light-dark(#231c12, #f6efe3);
  --boing-success: light-dark(#2f8f4e, #6fd394);
  --boing-radius: 14px;
}
```

| Variable | Default | Controls |
| --- | --- | --- |
| `--boing-bg` | `#fff` / `#0c0c0d` | Toast surface (light / dark). |
| `--boing-fg` | `#0f0f13` / `#fafafa` | Text and neutral icons. |
| `--boing-ring` | faint black / white | The 1px outline around the toast. |
| `--boing-shadow` | ring + soft drop shadow | The full box shadow. |
| `--boing-success` | `#12a36b` / `#4ade80` | Success icon colour. |
| `--boing-error` | `#e5484d` / `#f87171` | Error icon colour. |
| `--boing-warning` | `#c77d00` / `#fbbf24` | Warning icon colour. |
| `--boing-info` | `#2f7de1` / `#60a5fa` | Info icon colour. |
| `--boing-size` | `44px` | Height of the closed toast and size of the icon area. |
| `--boing-radius` | `22px` | Corner radius. `0` gives square corners. |
| `--boing-gap` | `8px` | Space between toasts in a list. |
| `--boing-pad` | `16px` | Distance from the edge of the screen. |
| `--boing-stack-offset` | `10px` | How far each older toast peeks out behind the newest. |
| `--boing-stack-scale` | `.05` | How much smaller each older toast gets. |
| `--boing-enter-scale` | `0.5` | Scale a toast starts from as it arrives. |
| `--boing-stretch` | `1` | Squash and stretch while moving. `0` turns it off. |

### Classes and attributes

Each toast is a `.boing` element with `data-type` (`success`, `error`, …) and `data-phase` attributes. Inside it are `.boing-title`, `.boing-desc`, `.boing-action` and `.boing-close`. The `className` option adds your own class to one toast, and the viewport carries `data-theme` and `data-position`.

```css
.boing.toast-brand {
  --fill: #1d4ed8;
  --on: #fff;
  --c: #fff;
}
```

The [playground](https://boing.aayushbharti.in/playground/) lets you try looks like this one and copy the CSS.

## Sound

Toasts are silent by default. Turn on the built-in chime and each type gets its own short cue: rising for success, falling for error, a double tap for warning and a single note for info. Loading toasts stay silent. The tones are synthesised with the Web Audio API, so there are no audio files to load.

```ts
toast.configure({ sound: true, volume: 0.5 });

toast.success('Payment received');
toast.error('Card declined');
```

Pass a function as `sound` to play your own audio; it receives the toast type. The chime itself is exported as `chime(type, volume)`. Browsers block audio until the visitor has interacted with the page, which suits toasts that follow a click.

## Is Boing accessible?

Yes. Screen readers, keyboards and reduced motion are handled without any setup:

- Toasts live in a landmark region named "Notifications". Messages are read through a polite status region, and errors through an assertive alert region. The toast itself carries no live role, so nothing is read twice.
- <kbd>Alt</kbd>+<kbd>T</kbd> moves focus to the toast's first button, or to the toast itself. <kbd>Esc</kbd> dismisses all toasts, except while focus is inside a dialog, menu, listbox or form field.
- Hovering a toast or focusing it with the keyboard pauses every timer, and leaving resumes it.
- Toasts that stay on screen get a close button labelled "Dismiss notification", unless they already have a secondary button. Buttons are only in the tab order while the toast is open.
- Buttons have a hit area at least 44px tall. A toast can also be dragged or flicked away.
- With reduced motion on, toasts fade in at their final size, and icon animations, the spinner and the countdown line are off.
- Right-to-left pages mirror the reveal direction and the countdown line.

Translate the two built-in labels with the `labels` prop:

```tsx
<Toaster labels={{ region: 'Benachrichtigungen', dismiss: 'Benachrichtigung schließen' }} />
```

## Frequently asked questions

### Is there a stylesheet to add?

No. The Toaster adds its own stylesheet to the start of `<head>` when it mounts. Your own CSS comes later in the page, so it overrides the defaults.

### Can several toasts be on screen at once?

By default a new toast morphs the one already showing. Set `toast.configure({ held: 'list' })` to keep sticky toasts, like errors, on screen while quick ones appear beside them, or `'queue'` to make new toasts wait their turn.

### Does Boing work with React Server Components?

Yes. The package is marked as client code, so a server layout can render `<Toaster />`. Call `toast` from client components, for example in an event handler.

### How do I keep a toast open until the user closes it?

Pass `duration: 0`. By default three kinds already wait for the user: errors, loading toasts and toasts with a button. Toasts that stay open get a close button unless they have a secondary button.

## Related guides

- [React toast notifications](https://boing.aayushbharti.in/react-toast/): One component and one function call.
- [Next.js toast notifications in the App Router (Boing)](https://boing.aayushbharti.in/nextjs-toast/): Toasts in a server-first app.
- [Loading toast](https://boing.aayushbharti.in/loading-toast/): One toast from loading to done.
- [Undo toast](https://boing.aayushbharti.in/undo-toast/): Act first, offer undo.
- [Accessible toast notifications](https://boing.aayushbharti.in/toast-accessibility/): Toasts screen readers and keyboards can use.
- [Toast playground](https://boing.aayushbharti.in/playground/): Pick a style, tweak it, copy the code.

Source: https://boing.aayushbharti.in/docs/
