An opinionated toast component for React.
'use client';
import React from 'react';
import { Toaster, toast } from 'sonner';
import { action } from '@/app/action';
const promise = () => new Promise((resolve) => setTimeout(resolve, 2000));
// Rendered above the <Toaster />, so its effect runs before the Toaster subscribes.
function ToastOnMount() {
React.useEffect(() => {
// Fixed id so StrictMode's double effect doesn't render two toasts
toast('Toast rendered on mount', { id: 'toast-on-mount' });
}, []);
return null;
}
export default function Home({ searchParams }: any) {
const [showAutoClose, setShowAutoClose] = React.useState(false);
const [showDismiss, setShowDismiss] = React.useState(false);
const [theme, setTheme] = React.useState(searchParams.theme || 'light');
const [isFinally, setIsFinally] = React.useState(false);
const [showAriaLabels, setShowAriaLabels] = React.useState(false);
const [historySize, setHistorySize] = React.useState<number | null>(null);
return (
<>
{searchParams.toastOnMount === '' ? <ToastOnMount /> : null}
<button data-testid="theme-button" className="button" onClick={() => setTheme('dark')}>
Change theme
</button>
<button data-testid="default-button" className="button" onClick={() => toast('My Toast')}>
Render Toast
</button>
<button data-testid="default-button-top" className="button" onClick={() => toast('My Toast')}>
Render Toast Top
</button>
<button data-testid="success" className="button" onClick={() => toast.success('My Success Toast')}>
Render Success Toast
</button>
<button data-testid="error" className="button" onClick={() => toast.error('My Error Toast')}>
Render Error Toast
</button>
<button
data-testid="action"
className="button"
onClick={() =>
toast('My Message', {
action: {
label: 'Action',
onClick: () => console.log('Action'),
},
})
}
>
Render Action Toast
</button>
<button
data-testid="action-prevent"
className="button"
onClick={() =>
toast('My Message', {
action: {
label: 'Action',
onClick: (event) => {
event.preventDefault();
console.log('Action');
},
},
})
}
>
Render Action Toast
</button>
<button
data-testid="promise"
data-finally={isFinally ? '1' : '0'}
className="button"
onClick={() =>
toast.promise(promise, {
loading: 'Loading...',
success: 'Loaded',
error: 'Error',
finally: () => setIsFinally(true),
})
}
>
Render Promise Toast
</button>
<button
data-testid="rsf-promise"
data-finally={isFinally ? '1' : '0'}
className="button"
onClick={() =>
toast.promise(action(), {
loading: 'Loading...',
success: 'Loaded',
error: 'Error',
finally: () => setIsFinally(true),
})
}
>
Render React Server Function Toast
</button>
<button
data-testid="custom"
className="button"
onClick={() =>
toast.custom((t) => (
<div>
<h1>jsx</h1>
<button data-testid="dismiss-button" onClick={() => toast.dismiss(t)}>
Dismiss
</button>
</div>
))
}
>
Render Custom Toast
</button>
<button
data-testid="custom-cancel-button-toast"
className="button"
onClick={() =>
toast('My Custom Cancel Button', {
cancel: {
label: 'Cancel',
onClick: () => console.log('Cancel'),
},
})
}
>
Render Custom Cancel Button
</button>
<button
data-testid="custom-with-empty-id"
className="button"
onClick={() =>
toast.custom(
(t) => (
<div>
<h1>jsx</h1>
<button data-testid="dismiss-button" onClick={() => toast.dismiss(t)}>
Dismiss
</button>
</div>
),
{
id: undefined,
},
)
}
>
Render Custom Toast with empty id
</button>
<button data-testid="infinity-toast" className="button" onClick={() => toast('My Toast', { duration: Infinity })}>
Render Infinity Toast
</button>
<button
data-testid="auto-close-toast-callback"
className="button"
onClick={() =>
toast('My Toast', {
onAutoClose: () => setShowAutoClose(true),
})
}
>
Render Toast With onAutoClose callback
</button>
<button
data-testid="dismiss-toast-callback"
className="button"
onClick={() =>
toast('My Toast', {
onDismiss: () => {
setShowDismiss(true);
},
})
}
>
Dismiss toast callback
</button>
<button
data-testid="non-dismissible-toast"
className="button"
onClick={() =>
toast('My Toast', {
dismissible: false,
})
}
>
Non-dismissible Toast
</button>
<button
data-testid="update-toast"
className="button"
onClick={() => {
const toastId = toast('My Unupdated Toast', {
duration: 10000,
});
toast('My Updated Toast', {
id: toastId,
duration: 10000,
});
}}
>
Updated Toast
</button>
<button
data-testid="update-toast-duration"
className="button"
onClick={() => {
const toastId = toast('My Unupdated Toast, Updated After 3 Seconds', {
duration: 10000,
});
setTimeout(() => {
toast('My Updated Toast, Close After 1 Second', {
id: toastId,
duration: 1000,
});
}, 3000);
}}
>
Updated Toast Duration
</button>
<button
data-testid="string-description"
className="button"
onClick={() => toast('Custom Description', { description: 'string description' })}
>
String Description
</button>
<button
data-testid="react-node-description"
className="button"
onClick={() => toast('Custom Description', { description: <div>This is my custom ReactNode description</div> })}
>
ReactNode Description
</button>
<button
data-testid="close-button"
className="button"
onClick={() => toast('Toast with close button', { closeButton: true })}
>
Render close button
</button>
<button
data-testid="extended-promise"
className="button"
onClick={() =>
toast.promise(
new Promise((resolve) => {
setTimeout(() => {
resolve({ name: 'Sonner' });
}, 2000);
}),
{
loading: 'Loading...',
success: (data: any) => ({
message: `${data.name} toast has been added`,
description: 'Custom description for the Success state',
}),
error: {
message: 'An error occurred',
description: undefined,
action: {
label: 'Retry',
onClick: () => {
console.log('retrying');
},
},
},
description: 'Global description',
},
)
}
>
Extended Promise Toast
</button>
<button
data-testid="extended-promise-error"
className="button"
onClick={() =>
toast.promise(
new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Simulated error'));
}, 2000);
}),
{
loading: 'Loading...',
success: (data: any) => ({
message: `${data.name} toast has been added`,
description: 'Custom description for the Success state',
}),
error: {
message: 'An error occurred',
description: undefined,
action: {
label: 'Retry',
onClick: (event) => {
event.preventDefault();
console.log('retrying');
},
},
},
description: 'Global description',
},
)
}
>
Extended Promise Error Toast
</button>
<button
data-testid="error-promise"
className="button"
onClick={() => {
const whatWillHappen = async () => {
throw new Error('Not implemented');
};
toast.promise(whatWillHappen, {
loading: 'Saving project...',
success: (result: any) => {
if (result?.ok) {
return 'Project saved';
} else {
return `${result?.error}`;
}
},
error: (e) => `Error Raise: ${e}`,
});
}}
>
Error Promise Toast
</button>
<button
className="button"
onClick={() => {
setShowAriaLabels(true);
toast('Toast with custom ARIA labels', { closeButton: true, onAutoClose: () => setShowAriaLabels(false) });
}}
>
With custom ARIA labels
</button>
<button
data-testid="toast-secondary"
className="button"
onClick={() => toast('Secondary Toaster Toast', { toasterId: 'secondary' })}
>
Render Toast in Secondary Toaster
</button>
<button data-testid="toast-global" className="button" onClick={() => toast('Global Toaster Toast')}>
Render Toast in Global Toaster
</button>
<button
data-testid="testid-toast-button"
className="button"
onClick={() => toast('Toast with test ID', { testId: 'my-test-toast' })}
>
Toast with testId
</button>
<button
data-testid="testid-promise-toast-button"
className="button"
onClick={() =>
toast.promise(promise, {
loading: 'Loading...',
success: 'Loaded',
error: 'Error',
testId: 'promise-test-toast',
})
}
>
Promise Toast with testId
</button>
<button
data-testid="promise-custom-icon"
className="button"
onClick={() =>
toast.promise(promise, {
loading: 'Loading...',
success: () => ({
message: 'Loaded',
icon: <span data-testid="custom-success-icon">✓</span>,
}),
error: 'Error',
})
}
>
Promise Toast with custom success icon
</button>
<button
data-testid="reused-id-with-action"
className="button"
onClick={() =>
toast.error('Toast with action', {
id: 'reused-id',
duration: 1000,
action: {
label: 'Action',
onClick: () => console.log('Action'),
},
})
}
>
Toast with action and a fixed id
</button>
<button
data-testid="reused-id-without-action"
className="button"
onClick={() => toast.success('Toast without action', { id: 'reused-id', duration: 10000 })}
>
Toast without action and the same fixed id
</button>
<button
data-testid="history-flood"
className="button"
onClick={() => {
for (let i = 0; i < 120; i++) {
toast.dismiss(toast(`Flood ${i}`, { duration: 1 }));
}
setHistorySize(toast.getHistory().length);
}}
>
Create and dismiss a lot of toasts
</button>
{historySize !== null ? <div data-testid="history-size">{historySize}</div> : null}
<button
data-testid="loading-toast-fixed-id"
className="button"
onClick={() => toast.loading('Loading', { id: 'fixed-id' })}
>
Loading toast with a fixed id
</button>
<button
data-testid="default-toast-fixed-id"
className="button"
onClick={() => toast('Done', { id: 'fixed-id', duration: 10000 })}
>
Default toast with the same fixed id
</button>
<button
data-testid="custom-toast-fixed-id"
className="button"
onClick={() => toast.custom(() => <div>Custom done</div>, { id: 'fixed-id', duration: 10000 })}
>
Custom toast with the same fixed id
</button>
<button
data-testid="dismiss-and-recreate"
className="button"
onClick={() => {
// What React does in StrictMode: effect, cleanup, effect
toast.warning('Remounted toast', { id: 'remounted', duration: 10000 });
toast.dismiss('remounted');
toast.warning('Remounted toast', { id: 'remounted', duration: 10000 });
}}
>
Dismiss and recreate a toast synchronously
</button>
<button
data-testid="react-node-description-wide"
className="button"
onClick={() =>
toast('Title', {
duration: 10000,
description: <div data-testid="wide-description" style={{ width: '100%', height: 8 }} />,
})
}
>
ReactNode description that fills the width
</button>
{showAutoClose ? <div data-testid="auto-close-el" /> : null}
{showDismiss ? <div data-testid="dismiss-el" /> : null}
<Toaster
offset={32}
position={searchParams.position || 'bottom-right'}
swipeDirections={searchParams.swipeDirections ? searchParams.swipeDirections.split(',') : undefined}
toastOptions={{
actionButtonStyle: { backgroundColor: 'rgb(219, 239, 255)' },
cancelButtonStyle: { backgroundColor: 'rgb(254, 226, 226)' },
closeButtonAriaLabel: showAriaLabels ? 'Yeet the notice' : undefined,
classNames: {
default: 'default-toast-classname',
success: 'success-toast-classname',
},
}}
theme={theme}
dir={searchParams.dir || 'auto'}
containerAriaLabel={showAriaLabels ? 'Notices' : undefined}
icons={{
close:
searchParams.customCloseIcon === '' ? (
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="12"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="3"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
) : undefined,
}}
/>
<Toaster
id="secondary"
position="top-left"
toastOptions={{
className: 'secondary-toaster',
}}
/>
</>
);
}
Home.theme = 'light';