Skip to Content
CodeUI

Toast

@codeui/solid v0.3.0

Short notifications that appear over the page and dismiss themselves.

When to use

Use a toast to confirm the result of an action the user just took, such as an export, a copy, or a save. The toast appears at a viewport edge, does not move focus, and closes on its own. The user can keep working while it is open.

When to choose another component

  • Use Alert when the message belongs to a place on the page and must stay there, such as a failed import above the file list. An alert stays until its cause is gone. A toast closes after a few seconds.
  • Use an inline error on the field, such as the errorMessage of TextField, when one input is wrong. The error sits where the user fixes it.
  • Use Dialog when the user must decide before they continue.
  • Use a Spinner or a loading Button for progress inside a control. A toast reports progress only for work that outlives the control, such as an upload.

Show notifications compares these choices with examples.

Live demo

toast/basic.tsx
import { Button, createToaster, Toaster } from "@codeui/solid";

export default function ToastBasic() {
	const notifications = createToaster();
	return (
		<>
			<Button
				variant="primary"
				onClick={() =>
					notifications.show({ tone: "success", description: "Snippet exported as PNG." })
				}
			>
				Export
			</Button>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

createToaster() returns a controller. Toaster renders the region that shows the controller's toasts. Call show from any event handler.

Anatomy

Tap a part to outline it in the demo.

  1. 01Regiontoast-regionclasses.region
  2. 02Listtoast-listclasses.list
  3. 03Roottoastclasses.root
  4. 04Icontoast-iconclasses.icon
  5. 05Titletoast-titleclasses.title
  6. 06Descriptiontoast-descriptionclasses.description
  7. 07Actiontoast-actionclasses.action
  8. 08CloseButtontoast-close-buttonclasses.closeButton
  9. 09ProgressTracktoast-progress-trackclasses.progressTrack
  10. 10ProgressFilltoast-progress-fillclasses.progressFill

Toaster renders Region and List. Each toast renders Root and the parts inside it. The ready toast never renders ProgressTrack or ProgressFill.

ExportRendersclasses keydata-cuiRole
Regiondiv, fixed to a viewport edgeregiontoast-regionregion
Listdiv that holds the visible toastslisttoast-listnone
Rootdiv, one toastroottoaststatus
Iconspan, the tone or custom iconicontoast-iconnone, aria-hidden
Titlediv, the bold first linetitletoast-titlenone
Descriptiondiv, the messagedescriptiontoast-descriptionnone
Actionbutton, an inline text actionactiontoast-actionbutton
CloseButtonbutton with a close iconcloseButtontoast-close-buttonbutton
ProgressTrackdiv, the track of a time barprogressTracktoast-progress-trackpresentation, aria-hidden
ProgressFilldiv, the fill of the time barprogressFilltoast-progress-fillnone

Region also sets data-position. Root sets data-tone. A toast from Toaster also sets data-cui-theme to its resolved theme, unless theme is page.

Variants

Tones

toast/tones.tsx
import { Button, createToaster, Toaster, type ToastOptions } from "@codeui/solid";
import { For } from "solid-js";

const messages: ToastOptions[] = [
	{ tone: "neutral", description: "Snippet duplicated." },
	{ tone: "info", description: "A new theme pack is available in Settings." },
	{ tone: "success", description: "Snippet exported as PNG." },
	{ tone: "warning", description: "JetBrains Mono failed to load. Using the fallback font." },
	{ tone: "danger", title: "Export failed", description: "The image is larger than 16 MB." },
];

export default function ToastTones() {
	const notifications = createToaster();
	return (
		<>
			<For each={messages}>
				{message => (
					<Button variant="secondary" onClick={() => notifications.show(message)}>
						{message.tone}
					</Button>
				)}
			</For>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

The tone sets the icon and the accent color of the icon. Neutral has no icon. Danger toasts are announced assertively. The other tones are announced politely.

Positions

toast/positions.tsx
import { Button, createToaster, Toaster } from "@codeui/solid";
import type { ToastPosition } from "@codeui/solid/toast/parts";
import { For } from "solid-js";

const positions: ToastPosition[] = [
	"top-left",
	"top-center",
	"top-right",
	"bottom-left",
	"bottom-center",
	"bottom-right",
];

export default function ToastPositions() {
	// A Toaster has one position. Each position needs its own controller.
	const toasters = positions.map(position => ({ position, toaster: createToaster() }));
	return (
		<For each={toasters}>
			{({ position, toaster }) => (
				<>
					<Button
						variant="secondary"
						onClick={() => toaster.show({ description: `Shown at ${position}.` })}
					>
						{position}
					</Button>
					<Toaster
						toaster={toaster}
						position={position}
						closeLabel="Dismiss"
						aria-label={`Notifications, ${position}`}
					/>
				</>
			)}
		</For>
	);
}

A Toaster has one position. The default is bottom-center. Toasts rise from the bottom edge and drop from the top edge. To show toasts at two positions, create two controllers and two Toaster elements.

Content

toast/content.tsx
import { Button, createToaster, icons, Toaster } from "@codeui/solid";

export default function ToastContent() {
	const notifications = createToaster();
	return (
		<>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						title: "Snippet saved",
						description: "main.rs is in your workspace.",
					})
				}
			>
				Title and description
			</Button>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						tone: "success",
						description: (
							<span>
								Copied <strong>1200 × 800</strong> PNG to the clipboard.
							</span>
						),
					})
				}
			>
				JSX description
			</Button>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						description: toast => (
							<span>
								Export #{toast.id} finished.{" "}
								<a href="#downloads" onClick={() => toast.dismiss()}>
									Open downloads
								</a>
							</span>
						),
					})
				}
			>
				Callback description
			</Button>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						icon: <icons.CheckIcon />,
						description: "Alt text copied.",
					})
				}
			>
				Custom icon
			</Button>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						tone: "success",
						icon: null,
						description: "Preset applied.",
					})
				}
			>
				No icon
			</Button>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						theme: "light",
						description: "This toast uses the light theme on any page.",
					})
				}
			>
				Light theme
			</Button>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

title and description take JSX or a callback. The callback receives the toast context, { id, dismiss }, so the content can close its own toast. The content renders inside Toaster, so it reads the context of the providers around Toaster, such as the locale.

icon replaces the tone icon. icon: null hides it. theme picks the toast's theme. The default, inverted, renders the opposite of the theme around the Toaster, as CodeImage does: a light card on a dark page, and a dark card on a light page. It follows the page when the theme changes while the toast is open. page uses the page theme. light and dark force one.

Action

toast/action.tsx
import { Button, createToaster, Toaster } from "@codeui/solid";

export default function ToastAction() {
	const notifications = createToaster();
	const paste = () =>
		notifications.show({
			description: "Code pasted. Format it?",
			action: {
				label: "Format",
				onClick: toast => {
					// The toast stays open after the click. Close it yourself.
					toast.dismiss();
					notifications.show({ tone: "success", description: "Formatted with Prettier." });
				},
			},
		});
	return (
		<>
			<Button variant="secondary" onClick={paste}>
				Paste code
			</Button>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

action renders one inline text button beside the message. Its onClick receives the toast context. The toast stays open after the click, so call toast.dismiss() when the action is done. Keep one action per toast. For a second choice, use a dialog.

Duration

toast/duration.tsx
import { Button, createToaster, Toaster } from "@codeui/solid";

export default function ToastDuration() {
	// Every toast of this controller closes after 3 seconds unless it sets its own duration.
	const notifications = createToaster({ duration: 3000 });
	return (
		<>
			<Button
				variant="secondary"
				onClick={() => notifications.show({ description: "Theme switched to Dracula." })}
			>
				3 seconds
			</Button>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						description: "Rendering a 60-frame video. Hover to keep this open.",
						duration: 10000,
					})
				}
			>
				10 seconds
			</Button>
			<Button
				variant="secondary"
				onClick={() =>
					notifications.show({
						tone: "warning",
						description: "You are offline. Changes are saved on this device.",
						duration: Infinity,
					})
				}
			>
				Until dismissed
			</Button>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

A toast closes after 5000 ms. createToaster({ duration }) changes the default for every toast of the controller. The duration of a toast overrides it. Infinity keeps the toast open until the user or your code closes it.

Every timer of a Toaster pauses while the pointer is over its toasts or focus is inside them, and while the window is not focused. The timers resume when the pointer leaves, focus leaves, or the window gets focus back.

States

Loading and promise

toast/promise.tsx
import { Button, createToaster, Toaster } from "@codeui/solid";

const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

async function uploadGist(fail: boolean) {
	await wait(1500);
	if (fail) throw new Error("GitHub returned 503.");
	return { url: "https://gist.github.com/codeimage/4f2a" };
}

export default function ToastPromise() {
	const notifications = createToaster();
	const share = (fail: boolean) =>
		notifications.promise(() => uploadGist(fail), {
			loading: { description: "Uploading to GitHub Gist…" },
			success: gist => ({ title: "Gist created", description: gist.url }),
			error: reason => ({
				title: "Upload failed",
				description: reason instanceof Error ? reason.message : "Try again.",
			}),
		});
	return (
		<>
			<Button variant="secondary" onClick={() => share(false)}>
				Share as Gist
			</Button>
			<Button variant="secondary" onClick={() => share(true)}>
				Share, then fail
			</Button>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

promise(input, { loading, success, error }) shows loading until the promise settles. Then the same toast shows success or error. input is a promise or a function that returns one. The function runs at once, and an error it throws shows error.

  • The loading toast shows a Spinner as its icon and stays open. Set icon or duration in loading to change that.
  • success and error take options, or a function that receives the resolved value or the rejection reason.
  • The settled options replace the loading options. They are not merged. The tone defaults to success or danger, and the duration to the controller default.

Update, dismiss, and clear

toast/controller.tsx
import { Button, createToaster, Toaster, type ToastId } from "@codeui/solid";

export default function ToastController() {
	const notifications = createToaster();
	let syncId: ToastId | undefined;

	const start = () => {
		syncId = notifications.show({
			description: "Syncing 3 snippets…",
			duration: Infinity,
			closeable: false,
		});
	};
	const finish = () => {
		if (syncId === undefined) return;
		// A new duration restarts the close timer.
		notifications.update(syncId, {
			tone: "success",
			description: "3 snippets synced.",
			duration: 4000,
			closeable: true,
		});
	};
	const cancel = () => {
		if (syncId !== undefined) notifications.dismiss(syncId);
	};

	return (
		<>
			<Button variant="secondary" onClick={start}>
				Start sync
			</Button>
			<Button variant="secondary" onClick={finish}>
				Finish
			</Button>
			<Button variant="secondary" onClick={cancel}>
				Dismiss
			</Button>
			<Button variant="secondary" onClick={() => notifications.clear()}>
				Clear all
			</Button>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

show returns a ToastId. Keep it to change or close that toast later.

  • update(id, options) merges the options into the open toast. A new duration restarts the close timer. The toast stays in place and does not play its entrance again.
  • dismiss(id) closes the toast with its exit animation.
  • clear() dismisses every toast of the controller.

All three do nothing when the id is not open. A ToastId is a number scoped to its controller. Two controllers can return the same id.

Queue

A Toaster shows three toasts at once. Set limit to change that. A later toast waits until a visible one closes, and its timer starts when it appears.

Two toasters on one page

toast/isolated.tsx
import { Button, createToaster, Toaster } from "@codeui/solid";

export default function ToastIsolated() {
	const app = createToaster();
	const editor = createToaster({ duration: Infinity });
	return (
		<>
			<Button variant="secondary" onClick={() => app.show({ description: "Project renamed." })}>
				App toast
			</Button>
			<Button
				variant="secondary"
				onClick={() => editor.show({ tone: "info", description: "Line 42 has a lint warning." })}
			>
				Editor toast
			</Button>
			<Button variant="secondary" onClick={() => editor.clear()}>
				Clear editor toasts
			</Button>
			<Toaster toaster={app} closeLabel="Dismiss" aria-label="App notifications" />
			<Toaster
				toaster={editor}
				position="top-right"
				closeLabel="Dismiss"
				aria-label="Editor notifications"
			/>
		</>
	);
}

Each controller has its own toasts, ids, and default duration. clear() on one controller leaves the other's toasts open. Give each Toaster an aria-label so screen reader users can tell the regions apart.

Ready API

Toaster

Toaster renders the region and list that show one controller's toasts. Place it inside the app's providers.

Prop

Type

Inherited from Kobalte's toast region:

Prop

Type

createToaster

createToaster(options) returns a ToastController. Created inside a component, the controller dismisses its toasts when that component's owner is disposed.

Prop

Type

The controller has these members:

MemberDescription
show(options): ToastIdShows a toast and returns its id. On the server it shows nothing.
update(id, options): voidMerges options into the open toast. A new duration restarts its timer.
dismiss(id): voidCloses the toast with its exit animation.
clear(): voidDismisses every toast of this controller.
promise(input, options): ToastIdShows loading, then success or error in the same toast.
regionId: stringTies the controller to its Toaster. You do not pass it yourself.

show, update, and each state of promise take ToastOptions:

Prop

Type

The callbacks of title, description, icon, and action.onClick receive a ToastContext, { id: ToastId; dismiss: () => void }. ToastPromiseOptions<D> holds the loading, success, and error options of promise.

Styled parts API

Import the parts from @codeui/solid/toast/parts.

toast/parts.tsx
import { Button, icons } from "@codeui/solid";
import * as T from "@codeui/solid/toast/parts";
import { toaster } from "@kobalte/core/toast";
import { createUniqueId } from "solid-js";

export default function ToastParts() {
	// Each region gets its own id. Kobalte's toaster routes a toast to the
	// region named in `toaster.show`.
	const region = `export-progress-${createUniqueId()}`;

	const showExport = () =>
		toaster.show(
			props => (
				<T.Root toastId={props.toastId} tone="success" duration={8000}>
					<T.Icon>
						<icons.CheckIcon />
					</T.Icon>
					<T.Title>Snippet exported</T.Title>
					<T.Description>hello-world.png is in your downloads.</T.Description>
					<T.Action onClick={() => toaster.dismiss(props.toastId)}>Open folder</T.Action>
					<T.CloseButton aria-label="Dismiss" />
					<T.ProgressTrack>
						<T.ProgressFill />
					</T.ProgressTrack>
				</T.Root>
			),
			{ region },
		);

	return (
		<>
			<Button variant="primary" onClick={showExport}>
				Export with a time bar
			</Button>
			<T.Region regionId={region} position="bottom-right" aria-label="Export notifications">
				<T.List />
			</T.Region>
		</>
	);
}

The parts wrap Kobalte's toast. They need Kobalte's toaster engine from @kobalte/core/toast to show a toast. The kit does not re-export it, so add @kobalte/core to your app before you compose the parts. Pass the toastId the engine gives you to Root, and the region you pass to toaster.show to Region as regionId. Use the parts when one toast needs a layout that ToastOptions cannot give, such as a time bar. Use Toaster for everything else.

Root lays out its children in a grid. Put Icon, Title, Description, Action, CloseButton, and ProgressTrack directly inside Root, without a wrapper element. ProgressFill shrinks over the duration you set on Root.

Action

Renders a button with type="button" and the inline text style. It is not a Kobalte part and does not close the toast. ActionProps is the button element's attributes.

CloseButton

Wraps Kobalte's Toast.CloseButton, which closes the toast. It shows a close icon when it has no children. Pass a localized aria-label. Kobalte's English default is "Close".

Description

Wraps Kobalte's Toast.Description. The root names it with aria-describedby.

Icon

Renders a span with aria-hidden="true" in the tone color. It is not a Kobalte part. IconProps is the span element's attributes.

List

Wraps Kobalte's Toast.List and renders a div in place of Kobalte's ol. Toasts carry role="status", which a list item may not take. Pointer and focus inside the list pause the timers.

ProgressFill

Wraps Kobalte's Toast.ProgressFill. Its width follows the time left, through --kb-toast-progress-fill-width. The fill takes the tone color.

ProgressTrack

Wraps Kobalte's Toast.ProgressTrack. It spans the full width under the content and holds ProgressFill.

Region

Wraps Kobalte's Toast.Region, fixed to the viewport edge that position names.

Prop

Type

RegionProps also takes Kobalte's region options, such as limit and swipeDirection.

Root

Wraps Kobalte's Toast root and renders a div. It sets the announcement priority from the tone.

Prop

Type

RootProps also takes Kobalte's root options, such as onEscapeKeyDown and onSwipeEnd.

Title

Wraps Kobalte's Toast.Title. The root names itself with aria-labelledby pointing at the title.

Styles export

toastStyles

toastStyles maps each part name to a function that returns the part's class string. ToastStyles is its type.

FunctionVariants
regionposition
roottone
list, title, description, closeButton, progressTrack, progressFill, icon, actionnone

Call a function when you render your own element with the toast look and no toast behavior, such as a static preview of a toast in a settings page. The tone accent that icon and progressFill use is set by root, so call them inside an element that has the root class.

Accessibility

Keyboard

KeyAction
Alt+TMoves focus to the toast list. Set hotkey to change the keys.
TabMoves to the next toast, then to its action and close button.
Shift+TabMoves to the previous focusable element.
Enter or SpaceActivates the focused action or close button.
EscapeCloses the focused toast.

A swipe or a pointer drag to the right past a threshold closes the toast. A shorter drag returns it to its place. Set swipeDirection on Toaster to change the direction.

ARIA

  • The region has role="region" and the label "Notifications (alt+T)". Set aria-label to localize it. A {hotkey} placeholder in the label is replaced with the hotkey.
  • Each toast has role="status", aria-atomic="true", and aria-live="polite". A danger toast has aria-live="assertive". On the parts, set priority="high" or priority="low" on Root to choose. ToastOptions has no priority.
  • The toast is labelled by its title and described by its description.
  • The icon is hidden from assistive technology. The close button has the closeLabel of Toaster as its name.

Focus

Showing a toast does not move focus. Each toast is in the tab order. While focus is inside the list, every timer of the Toaster pauses, so a keyboard user can reach the action before the toast closes. Do not put the only way to finish a task in a toast. A toast that closes takes its action with it.

Reduced motion

A toast rises from the edge it sits on: it moves up its own height with a fade over --cui-motion-duration-rise (400ms), or drops by its height at the top edge. It leaves with a fade over --cui-motion-duration-panel (200ms). With prefers-reduced-motion: reduce, the entrance and the swipe exit are fades with no movement. A toast that follows the finger during a swipe still moves, because the user moves it.

SSR notes

  • Toaster renders the region and an empty list on the server. Toasts render only on the client.
  • show and promise on the server return an id and do nothing. Nothing is queued, so no toast reaches the client from a server render.
  • Create the controller inside a component, such as the app root, so that each request gets its own controller. A controller in a module is shared by every request in the server process. It holds no toasts on the server, but a per-component controller also cleans up with its owner. Show notifications shows the setup.
  • The region id is not rendered into the HTML, so it cannot cause a hydration mismatch.

Theming hooks

The toast reads these properties. Their defaults are in Tokens.

PropertyUsed for
--cui-surface-toast, --cui-text-toastToast fill and text
--cui-shadow-menuToast shadow
--cui-radius-card, --cui-radius-xs, --cui-radius-fullToast, button, and time bar corners
--cui-space-0-5, --cui-space-2, --cui-space-3, --cui-space-4Time bar height, gaps, toast padding, region padding
--cui-space-16Extra offset of bottom regions: with the region padding, toasts sit 80px above the bottom edge, clear of a bottom toolbar
--cui-font-family-sans, --cui-font-size-sm, --cui-font-size-md, --cui-font-line-height-snug, --cui-font-weight-semiboldText (14px / 1.3), icon size, title and action weight
--cui-action-brand-base, --cui-action-success-base, --cui-action-caution-base, --cui-action-danger-baseAccent of the info, success, warning, and danger tones
--cui-action-neutral-baseButton hover fill and time bar track
--cui-action-brand-soft-textAction text
--cui-text-mutedClose icon
--cui-focus-width, --cui-focus-color, --cui-focus-offsetFocus ring
--cui-motion-duration-rise, --cui-motion-duration-panel, --cui-motion-ease-outEntrance (Rise), exit and swipe return

Composition examples

  • Show notifications sets up one controller per request, and wraps an export in a promise toast with a retry action.
  • Alert stays in place on the page until its cause is gone.
  • Dialog blocks the page until the user decides.
  • Spinner shows progress inside the control that started the work.

On this page