Skip to Content
CodeUI

Show notifications

@codeui/solid v0.3.0

Report the result of an action with toasts.

This guide shows how to set up toasts in an app, pick between a toast and the other messages, and report an async export with a promise toast. The Toast page lists every option.

Choose a toast, an alert, or an inline message

Ask where the user needs the message and how long it stays true.

MessageUseExample
The result of an action the user just took. It stays true after it disappears.A toast"Snippet exported as PNG."
A problem with one input that the user must fix before they continue.The field's errorMessage"The file name cannot contain /."
A condition of one part of the page that stays until its cause is gone.An Alert in that part"This project is read-only. Ask the owner for access."
A decision the user must make before they continue.A Dialog"Delete 3 snippets?"

A toast closes on its own, so never put the only copy of an error the user must act on in a toast. If an export fails, the toast can say so and offer a retry. If a form fails, mark the fields.

Create one controller per app render

show-notifications/app-setup.tsx
import { Button, createToaster, Toaster, type ToastController } from "@codeui/solid";
import { createContext, useContext } from "solid-js";
import { type JSX } from "@solidjs/web";

const NotificationsContext = createContext<ToastController>();

export function useNotifications() {
	const controller = useContext(NotificationsContext);
	if (!controller) throw new Error("useNotifications needs a NotificationsProvider.");
	return controller;
}

/** Creates one controller per render, so each server request gets its own. */
function NotificationsProvider(props: { children: JSX.Element }) {
	const notifications = createToaster();
	return (
		<NotificationsContext value={notifications}>
			{props.children}
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</NotificationsContext>
	);
}

function SaveButton() {
	const notifications = useNotifications();
	return (
		<Button
			variant="primary"
			onClick={() => notifications.show({ tone: "success", description: "Preset saved." })}
		>
			Save preset
		</Button>
	);
}

export default function AppSetup() {
	return (
		<NotificationsProvider>
			<SaveButton />
		</NotificationsProvider>
	);
}
  1. Create the controller inside a component near the root of the app. On the server, each request renders its own root, so each request gets its own controller.
  2. Render Toaster inside your locale and theme providers. Toast content renders inside Toaster and reads their context.
  3. Pass the controller down with a context. Components call useNotifications().show(...).

show on the server does nothing, so code that runs during the server render cannot leak a toast into another request. If your app renders only on the client, you can export one controller from a module and import it where you need it.

Wrap an async export in a promise toast

show-notifications/export-flow.tsx
import { Button, createToaster, Toaster } from "@codeui/solid";

const snippet = `fn main() {\n    println!("Hello, CodeImage");\n}`;

/** Draws the snippet on a canvas and encodes it as a PNG. */
async function renderPng(code: string, scale: number): Promise<Blob> {
	const canvas = document.createElement("canvas");
	canvas.width = 640 * scale;
	canvas.height = 240 * scale;
	const context = canvas.getContext("2d");
	if (!context) throw new Error("This browser cannot draw the image.");
	context.scale(scale, scale);
	context.fillStyle = "#1e1e2e";
	context.fillRect(0, 0, 640, 240);
	context.fillStyle = "#cdd6f4";
	context.font = "16px ui-monospace, monospace";
	code.split("\n").forEach((line, index) => context.fillText(line, 32, 64 + index * 24));
	const blob = await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, "image/png"));
	if (!blob) throw new Error("The image is too large to encode. Lower the scale.");
	return blob;
}

function download(blob: Blob, fileName: string) {
	const url = URL.createObjectURL(blob);
	const link = document.createElement("a");
	link.href = url;
	link.download = fileName;
	link.click();
	setTimeout(() => URL.revokeObjectURL(url), 1000);
}

export default function ExportFlow() {
	const notifications = createToaster();

	const exportPng = (scale: number) =>
		notifications.promise(() => renderPng(snippet, scale), {
			loading: { description: `Exporting main.rs at ${scale}×…` },
			success: blob => {
				download(blob, `main-rs@${scale}x.png`);
				return { description: `main-rs@${scale}x.png saved (${Math.round(blob.size / 1024)} KB).` };
			},
			error: reason => ({
				title: "Export failed",
				description: reason instanceof Error ? reason.message : "Try again.",
				duration: Infinity,
				action: {
					label: "Retry at 1×",
					onClick: toast => {
						toast.dismiss();
						exportPng(1);
					},
				},
			}),
		});

	return (
		<>
			<Button variant="primary" onClick={() => exportPng(2)}>
				Export PNG
			</Button>
			<Button variant="secondary" onClick={() => exportPng(64)}>
				Export at 64×
			</Button>
			<Toaster toaster={notifications} closeLabel="Dismiss" />
		</>
	);
}

notifications.promise shows the loading toast at once and swaps it for the result in the same place. The example draws the snippet on a canvas, encodes a PNG, and downloads it. Export at 64× asks for a canvas wider than browsers allow, so the drawing or the encoding fails and the error state shows.

  • Pass a function, () => renderPng(snippet, scale), to start the work inside promise. An error it throws shows the error state too.
  • Use the success callback for the follow-up work that needs the result, here the download. Return the options of the success toast.
  • Give the error toast duration: Infinity so it stays until the user reads it. Add a retry action. The action does not close the toast, so call toast.dismiss() first.

Show toasts in two places

Create a second controller and a second Toaster with its own position and aria-label. Each controller keeps its own toasts, ids, and default duration, and clear() on one leaves the other open. The Toast page has the demo. Keep one controller unless the second region serves a separate part of the app, such as an editor panel.

Write the message

  • Say what happened, in the past tense, with the object name: "main-rs@2x.png saved", not "Success".
  • For a failure, say what failed and what to do next, in the title and the description.
  • Use the danger tone only for failures. Danger toasts interrupt screen reader users.
  • Keep one action, labelled with a verb, such as "Retry" or "Undo".
  • Do not use a toast to announce new features. Use a dot on the control, as Patterns describes.

On this page