Documentation / Feedback & overlays
Toaster
The container of the toasts. Mounted once, near the root of the application, it draws the messages pushed with toast() — from a component, an event handler or a module that is not a component — or with useToast(). A server layout can render it: it takes no function.
The newest are shown nearest the edge, max at a time (three by default); the others wait their turn without counting down, and none is lost. Each toast closes on its own after duration (5 seconds by default, 0 keeps it), and a line along its bottom shows the time left. The countdowns stop while the pointer is over the stack, while the focus is in it or while the page is hidden, then start over.
One polite live region announces each toast. It stays readable and clickable while a dialog hides the rest of the page, and F8 sends the focus there: Tab goes from one toast to the next, Escape or Tab past the last one goes back to where it was. For a message placed somewhere on the page, see Toast.
Examples
Basic usage
One <Toaster /> mounted once, and toast() called from wherever.
import { Button, Toaster, toast } from "@synertech/ui";
export function Basic() {
return (
<>
<Button
onClick={() =>
toast.success("Facture envoyée", {
description: "Le client la reçoit dans un instant.",
})
}
>
Envoyer la facture
</Button>
<Toaster />
</>
);
}Types
toast.success, toast.error, toast.warning and toast.info pick the colour and the icon.
import { Button, Toaster, toast } from "@synertech/ui";
export function Types() {
return (
<>
<div className="flex flex-wrap gap-2">
<Button onClick={() => toast.success("Paiement reçu")}>Succès</Button>
<Button onClick={() => toast.error("Paiement refusé")}>Erreur</Button>
<Button onClick={() => toast.warning("Stockage à 90 %")}>Avertissement</Button>
<Button onClick={() => toast.info("Nouvelle version disponible")}>Info</Button>
</div>
<Toaster />
</>
);
}Undoing an action
action adds a button; onClose says why the toast left, which decides whether the deletion goes through.
import { useState } from "react";
import { Button, Toaster, toast } from "@synertech/ui";
export function UndoAction() {
const [files, setFiles] = useState(["rapport-mars.pdf", "devis-42.pdf", "contrat.pdf"]);
const [log, setLog] = useState<string[]>([]);
const remove = (name: string) => {
setFiles((current) => current.filter((file) => file !== name));
toast("Fichier supprimé", {
description: name,
action: {
label: "Annuler",
onClick: () => setFiles((current) => [...current, name]),
},
onClose: (reason) => {
if (reason !== "action") setLog((current) => [...current, `${name} supprimé`]);
},
});
};
return (
<>
<ul className="space-y-2">
{files.map((name) => (
<li key={name} className="flex items-center justify-between gap-4">
<span>{name}</span>
<Button size="sm" onClick={() => remove(name)}>
Supprimer
</Button>
</li>
))}
</ul>
{log.length > 0 && (
<p className="mt-3 text-sm text-gray-500 dark:text-gray-400">{log.join(", ")}</p>
)}
<Toaster />
</>
);
}Following a promise
toast.promise shows a loading toast, replaced by the success or the error; the promise is handed back as it is.
import { Button, Toaster, toast } from "@synertech/ui";
const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
export function PromiseToast() {
const save = async (fail: boolean) => {
await wait(1500);
if (fail) throw new Error("Le serveur n’a pas répondu.");
return 12;
};
const run = (fail: boolean) =>
toast
.promise(save(fail), {
loading: "Enregistrement…",
success: (rows) => `${rows} lignes enregistrées`,
error: (error) => ({
title: "Échec de l’enregistrement",
description: error instanceof Error ? error.message : undefined,
action: { label: "Réessayer", onClick: () => run(false) },
}),
})
// Le toast a dit l’erreur : rien d’autre à faire ici.
.catch(() => {});
return (
<>
<div className="flex gap-2">
<Button onClick={() => run(false)}>Enregistrer</Button>
<Button onClick={() => run(true)}>Enregistrer (échec)</Button>
</div>
<Toaster />
</>
);
}Replacing a toast
Pushed again under the same id, a toast is replaced in place and its countdown starts over.
import { Button, Toaster, toast } from "@synertech/ui";
const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
export function ReplaceById() {
const upload = async () => {
for (let part = 1; part <= 3; part++) {
toast.loading(`Envoi de la pièce ${part} sur 3…`, { id: "upload" });
await wait(800);
}
toast.success("Pièces envoyées", { id: "upload" });
};
return (
<>
<Button onClick={upload}>Envoyer trois pièces</Button>
<Toaster />
</>
);
}Position, stack and duration
position picks the corner, max how many toasts are shown, duration the default delay.
import { Button, Toaster, toast } from "@synertech/ui";
export function PositionAndStack() {
let count = 0;
return (
<>
<Button onClick={() => toast(`Message ${++count}`)}>Ajouter un message</Button>
<Toaster position="top-center" max={2} duration={3000} variant="solid" />
</>
);
}From a dialog
The toast stays readable and clickable over the dialog; F8 sends the focus there, Escape brings it back into the dialog.
import { useState } from "react";
import { Button, Modal, Toaster, toast, useToast } from "@synertech/ui";
export function FromADialog() {
const [open, setOpen] = useState(false);
const notify = useToast();
return (
<>
<Button onClick={() => setOpen(true)}>Modifier le client</Button>
<Modal
isOpen={open}
onClose={() => setOpen(false)}
title="Modifier le client"
showSubmit
submitLabel="Enregistrer"
onSubmitClick={() => {
notify.success("Client enregistré", {
action: { label: "Fermer la fenêtre", onClick: () => setOpen(false) },
});
// La modale reste ouverte : le toast s’affiche devant elle.
return false;
}}
>
<p className="text-sm">Appuyez sur Enregistrer, puis sur F8 pour atteindre le toast.</p>
</Modal>
<Toaster />
</>
);
}API reference
Components
Draws the toasts pushed with toast() or useToast(). Mount one, near the root of the application: a server layout can render it, it takes no function.
One live region speaks for the stack, polite for every type — an error is read after what is being read, not over it: a toast is not where an application stops its reader, a dialog is. The region stays readable and clickable while a dialog hides the page, sits above dialogs and menus, and is rendered under the <body> of the document it is shown in.
The countdowns are held while the pointer is over the stack, while the focus is in it and while the page is hidden, and start over when that ends.
import { Toaster } from "@synertech/ui";Props — ToasterProps
| Prop | Type | Default | Description |
|---|---|---|---|
className |
string |
— | Classes of the region. |
closable |
boolean |
true |
Shows the close button of a toast that did not say. |
duration |
number |
5000 |
Milliseconds a toast stays when it was given no |
hotkey |
string | false |
"F8" |
The key that sends the focus to the toasts, as |
label |
string |
— | Accessible name of the region. Defaults to the |
max |
number |
3 |
The most toasts shown at once. The newest are shown; the others wait, without counting down, and come back as the shown ones close — none is dropped unread. |
position |
ToastPosition |
"bottom-right" |
Corner of the viewport the toasts stack in. The newest is the one nearest the edge. |
showProgress |
boolean |
true |
Draws, along the bottom of a toast that counts down, the time it has left. |
variant |
ToastVariant |
"soft" |
Visual variant of a toast that was given none. |
Hooks
The function that pushes a toast to the <Toaster />: toast itself, for a component that would rather ask a hook. Stable from one render to the next.
import { useToast } from "@synertech/ui";useToast(): ToastApiFunctions
toast
FunctionPushes a toast to the <Toaster /> of the application, from anywhere — a component, an event handler, a module that is not a component. Returns the id of the toast. Does nothing on the server.
import { toast } from "@synertech/ui";toast(title: ReactNode, options?: ToastOptions): stringTypes
ToastAction
InterfaceThe button of a toast. Pressed, it calls onClick and closes the toast, unless onClick calls event.preventDefault().
interface ToastAction| Field | Type | Default | Description |
|---|---|---|---|
label• |
ReactNode |
— | Text of the button. |
onClick |
(event: MouseEvent<HTMLButtonElement>) => void |
— | Called when the button is pressed, before the toast closes. |
ToastApi
Interfaceinterface ToastApi| Field | Type | Default | Description |
|---|---|---|---|
dismiss• |
(id?: string) => void |
— | Closes a toast, or every toast when no id is given. |
error• |
(title: ReactNode, options?: ToastOptions) => string |
— | A toast of type |
info• |
(title: ReactNode, options?: ToastOptions) => string |
— | A toast of type |
loading• |
(title: ReactNode, options?: ToastOptions) => string |
— | A toast with a spinner, which stays until it is replaced under its id or closed. |
promise• |
(promise: Promise<Value> | (() => Promise<Value>), messages: ToastPromiseMessages<Value>, options?: ToastOptions) => Promise<Value> |
— | A loading toast replaced by |
success• |
(title: ReactNode, options?: ToastOptions) => string |
— | A toast of type |
warning• |
(title: ReactNode, options?: ToastOptions) => string |
— | A toast of type |
ToastContent
InterfaceA toast written as one object: its title and its options.
interface ToastContent extends ToastOptions| Field | Type | Default | Description |
|---|---|---|---|
action |
ToastAction |
— | A button under the text: "Undo", "Retry". |
className |
string |
— | Classes of the toast. |
closable |
boolean |
— | Shows the close button. Defaults to the Toaster's |
description |
ReactNode |
— | Text under the title. |
duration |
number |
— | Milliseconds before the toast closes on its own. Defaults to the Toaster's |
icon |
ReactNode |
— | Replaces the icon of the type. |
id |
string |
— | Names the toast. Pushing a toast under an id already shown replaces that toast in place, and starts its countdown over: how a message is updated. |
onClose |
(reason: ToastCloseReason) => void |
— | Called once when the toast leaves, with the reason. Not called when it is replaced under its |
title |
ReactNode |
— | |
type |
ToastType |
— | Colour and default icon. |
variant |
ToastVariant |
— | Visual variant. Defaults to the Toaster's |
ToastOptions
Interfaceinterface ToastOptions| Field | Type | Default | Description |
|---|---|---|---|
action |
ToastAction |
— | A button under the text: "Undo", "Retry". |
className |
string |
— | Classes of the toast. |
closable |
boolean |
— | Shows the close button. Defaults to the Toaster's |
description |
ReactNode |
— | Text under the title. |
duration |
number |
— | Milliseconds before the toast closes on its own. Defaults to the Toaster's |
icon |
ReactNode |
— | Replaces the icon of the type. |
id |
string |
— | Names the toast. Pushing a toast under an id already shown replaces that toast in place, and starts its countdown over: how a message is updated. |
onClose |
(reason: ToastCloseReason) => void |
— | Called once when the toast leaves, with the reason. Not called when it is replaced under its |
type |
ToastType |
— | Colour and default icon. |
variant |
ToastVariant |
— | Visual variant. Defaults to the Toaster's |
ToastPromiseMessages
Interfaceinterface ToastPromiseMessages<Value>| Field | Type | Default | Description |
|---|---|---|---|
loading• |
ReactNode | ToastContent |
— | Shown while the promise is pending. |
error |
ToastPromiseMessage<unknown> |
— | Replaces the loading toast once the promise rejects. Left out, the loading toast closes. |
success |
ToastPromiseMessage<Value> |
— | Replaces the loading toast once the promise resolves. Left out, the loading toast closes. |
ToastCloseReason
TypeWhy a toast left: its countdown ran out, its cross or its action was pressed, or toast.dismiss() was called.
type ToastCloseReason = "timeout" | "close" | "action" | "dismiss"What a stage of toast.promise() shows: a title, a whole toast, or a function of the value (or the error) returning either.
type ToastPromiseMessage<Value> = | ReactNode
| ToastContent
| ((value: Value) => ReactNode | ToastContent)