Search docs

Toast

A short message that appears for a moment, such as "Saved", without interrupting the user.

There is no WAI-ARIA APG pattern for toasts. Toasts are read out through a live region, live in a landmark that the keyboard can reach with a hotkey, and stay while the user is reading them.

import { component$, useSignal, useStyles$ } from '@builder.io/qwik';
import { Toast } from '@leve-ui/toast';
import { LuX } from '@qwikest/icons/lucide';
import styles from './default.css?inline';

const MESSAGES = [
  { title: 'Saved', description: 'Your changes were saved.' },
  { title: 'Copied', description: 'The link was copied to the clipboard.' },
  { title: 'Invitation sent', description: 'We emailed the invitation to your teammate.' },
];

// Any component inside the Provider can add toasts
const ShowButton = component$(() => {
  const toaster = Toast.useToaster();
  const count = useSignal(0);

  return (
    <button
      type="button"
      class="toast-default-button"
      onClick$={() => {
        toaster.add$(MESSAGES[count.value % MESSAGES.length]);
        count.value += 1;
      }}
    >
      Show toast
    </button>
  );
});

// Renders the toasts; put it once, usually at the app root
const Toaster = component$(() => {
  const toaster = Toast.useToaster();

  return (
    <Toast.Region class="toast-default-region">
      <Toast.List class="toast-default-list">
        {toaster.toasts.value.map((toast) => (
          <Toast.Root key={toast.id} toast={toast} class="toast-default-toast">
            <Toast.Title class="toast-default-title">{toast.title}</Toast.Title>
            <Toast.Description class="toast-default-description">
              {toast.description}
            </Toast.Description>
            <Toast.Close aria-label="Close" class="toast-default-close">
              <LuX aria-hidden="true" class="toast-default-icon" />
            </Toast.Close>
          </Toast.Root>
        ))}
      </Toast.List>
    </Toast.Region>
  );
});

export default component$(() => {
  useStyles$(styles);

  return (
    <Toast.Provider>
      <ShowButton />
      <Toaster />
    </Toast.Provider>
  );
});

Installation#

Install the individual package, or use @leve-ui/core to get every component at once:

pnpm add @leve-ui/toast

Anatomy#

import { Toast } from '@leve-ui/toast'; // or '@leve-ui/core'

<Toast.Provider>
  {/* Your app: call Toast.useToaster().add$() anywhere inside */}
  <Toast.Region>
    <Toast.List>
      {toaster.toasts.value.map((toast) => (
        <Toast.Root key={toast.id} toast={toast}>
          <Toast.Title />
          <Toast.Description />
          <Toast.Action />
          <Toast.Close />
        </Toast.Root>
      ))}
    </Toast.List>
  </Toast.Region>
</Toast.Provider>
PartElementDescription
Toast.ProviderNoneHolds the toasts and the settings. Wrap your app with it.
Toast.Region<section>The landmark that holds the toasts. The hotkey moves focus to it.
Toast.List<ol>The list of toasts.
Toast.Root<li>One toast. Takes a toast from useToaster().toasts.
Toast.Title<div>The title.
Toast.Description<div>Optional. The details.
Toast.Action<button>Optional. An action such as Undo. It closes the toast after its onClick$.
Toast.Close<button>Closes the toast.

Adding Toasts#

Toast.useToaster() returns the toasts and the functions that change them. Call it in any component inside the Provider.

const toaster = Toast.useToaster();

const id = await toaster.add$({ title: 'Uploading', duration: Infinity });
await toaster.update$(id, { title: 'Uploaded', duration: 3000 });
await toaster.dismiss$(id); // or dismiss$() to close all
OptionDescription
title / descriptionThe text, also used for the announcement.
type'foreground' (default) for results of a user action, announced right away. 'background' for background tasks, announced after the current speech.
durationHow long the toast stays, in ms. Infinity keeps it until it is closed. Defaults to the Provider's duration.
dataYour own data for rendering, typed with useToaster<T>(). It must be serializable.

The toasts are kept in a signal in the Provider's context, not in a module variable: each request on the server has its own toasts, and a toast added on the server shows up on the client.

Stacking#

Each toast outputs CSS variables to stack them like cards and spread them out while the pointer is over the Region or focus is in it (data-expanded). The demo above shows one way:

.toast {
  position: absolute;
  bottom: 0;
  transform: translateY(calc(var(--leve-toast-index) * -12px))
    scale(calc(1 - var(--leve-toast-index) * 0.05));
}

.toast[data-expanded] {
  transform: translateY(calc(-1 * var(--leve-toast-front-offset) - var(--leve-toast-index) * 12px));
}

Examples#

Action#

A toast with a Toast.Action stays until it is closed, so the user has time to reach it. Offer the same action elsewhere on the page too, since the toast goes away.

  • report.pdf
  • photo.png
  • notes.txt

API Reference#

Provider#

PropDefaultType
duration5000number

How long a toast stays, in ms. A toast with an Action stays until it is closed.

placement'bottom-end''top-start' | 'top' | 'top-end' | 'bottom-start' | 'bottom' | 'bottom-end'

Where the Region is placed. Output as data-placement on the Region and the toasts.

swipeDirection–'up' | 'down' | 'left' | 'right'

The direction to swipe a toast away. Defaults to the nearest edge of the placement.

swipeThreshold50number

How far a toast must be swiped to close it, in px.

hotkey['F8']string[]

The keys that move focus to the Region: KeyboardEvent.code values, and altKey, ctrlKey, metaKey or shiftKey for modifiers.

Region#

PropDefaultType
label'Notifications ({hotkey})'string

The name of the region. {hotkey} is replaced with the hotkey, e.g. F8.

Also accepts all <section> attributes.

Data attributeValue
data-leve-toast-regionAlways present
data-placementThe Provider's placement
data-expandedPresent while the pointer is over the Region or focus is in it

The library does not place the Region: use data-placement or your own class to position it.

List#

No props of its own. Accepts all <ol> attributes.

Data attributeValue
data-leve-toast-listAlways present
data-placementThe Provider's placement
data-expandedPresent while the pointer is over the Region or focus is in it

Root#

PropDefaultType
toast (required)–ToastData

The toast to render, from useToaster().toasts.

Also accepts all <li> attributes.

Data attributeValue
data-leve-toastAlways present
data-state"open" | "closed"
data-type"foreground" | "background"
data-placementThe Provider's placement
data-frontPresent on the newest open toast
data-expandedPresent while the pointer is over the Region or focus is in it
data-swipe"move" | "cancel" | "end" while or after swiping
data-swipe-direction"up" | "down" | "left" | "right"
CSS variableValue
--leve-toast-indexThe position from the front: 0 is the newest open toast
--leve-toast-countThe number of open toasts
--leve-toast-front-offsetThe total height of the newer toasts, to spread the stack
--leve-toast-heightThe height of this toast
--leve-toast-front-heightThe height of the front toast, e.g. to make the toasts behind it as tall
--leve-toast-swipe-move-x / -yThe distance swiped so far, while data-swipe="move"
--leve-toast-swipe-end-x / -yThe distance swiped, when data-swipe="end"

When closed, the toast gets data-state="closed" and is removed after its CSS animations and transitions finish, so you can animate it out.

Title#

No props of its own. Accepts all <div> attributes.

Data attributeValue
data-leve-toast-titleAlways present

Description#

No props of its own. Accepts all <div> attributes.

Data attributeValue
data-leve-toast-descriptionAlways present

Action#

No props of its own. Accepts all <button> attributes.

Data attributeValue
data-leve-toast-actionAlways present

Close#

No props of its own. Accepts all <button> attributes.

Data attributeValue
data-leve-toast-closeAlways present

Accessibility#

  • When a toast is added, its title and description are announced through a live region that is always on the page: assertive for foreground, polite for background. The toast itself is not a live region, since live regions added to the page are not reliably announced.
  • Toast.Region is a <section> landmark named "Notifications (F8)". Change the name with label; {hotkey} is replaced with the hotkey.
  • Toasts close on their own only while the user is not on them: the timer pauses while the pointer is over the Region, focus is in it, the window is in the background, or a toast is being swiped. A toast with an Action never closes on its own.
  • Give Toast.Close an aria-label when it shows only an icon.

Keyboard Interactions#

KeyDescription
F8Moves focus to the Region. Change it with the Provider's hotkey.
TabMoves through the toasts and their buttons.
EscapeOn a toast, closes it and moves focus to the next toast, or the Region.