Skip to content

An opinionated toast component for React.

feat(toaster): add support for multiple toasters with unique identifiers (#665)

Shintaro Jokagi0600a5cb4040
diff --git a/src/index.tsx b/src/index.tsx
index 807f000..f64a469 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -592,6 +592,7 @@ function useSonner() {
const Toaster = React.forwardRef<HTMLElement, ToasterProps>(function Toaster(props, ref) {
const {
+ id,
invert,
position = 'bottom-right',
hotkey = ['altKey', 'KeyT'],
@@ -612,11 +613,17 @@ const Toaster = React.forwardRef<HTMLElement, ToasterProps>(function Toaster(pro
containerAriaLabel = 'Notifications',
} = props;
const [toasts, setToasts] = React.useState<ToastT[]>([]);
+ const filteredToasts = React.useMemo(() => {
+ if (id) {
+ return toasts.filter((toast) => toast.toasterId === id);
+ }
+ return toasts.filter((toast) => !toast.toasterId);
+ }, [toasts, id]);
const possiblePositions = React.useMemo(() => {
return Array.from(
- new Set([position].concat(toasts.filter((toast) => toast.position).map((toast) => toast.position))),
+ new Set([position].concat(filteredToasts.filter((toast) => toast.position).map((toast) => toast.position))),
);
- }, [toasts, position]);
+ }, [filteredToasts, position]);
const [heights, setHeights] = React.useState<HeightT[]>([]);
const [expanded, setExpanded] = React.useState(false);
const [interacting, setInteracting] = React.useState(false);
@@ -776,7 +783,7 @@ const Toaster = React.forwardRef<HTMLElement, ToasterProps>(function Toaster(pro
{possiblePositions.map((position, index) => {
const [y, x] = position.split('-');
- if (!toasts.length) return null;
+ if (!filteredToasts.length) return null;
return (
<ol
@@ -836,7 +843,7 @@ const Toaster = React.forwardRef<HTMLElement, ToasterProps>(function Toaster(pro
}}
onPointerUp={() => setInteracting(false)}
>
- {toasts
+ {filteredToasts
.filter((toast) => (!toast.position && index === 0) || toast.position === position)
.map((toast, index) => (
<Toast
@@ -860,7 +867,7 @@ const Toaster = React.forwardRef<HTMLElement, ToasterProps>(function Toaster(pro
actionButtonStyle={toastOptions?.actionButtonStyle}
closeButtonAriaLabel={toastOptions?.closeButtonAriaLabel}
removeToast={removeToast}
- toasts={toasts.filter((t) => t.position == toast.position)}
+ toasts={filteredToasts.filter((t) => t.position == toast.position)}
heights={heights.filter((h) => h.position == toast.position)}
setHeights={setHeights}
expandByDefault={expand}
diff --git a/src/types.ts b/src/types.ts
index 92d033f..79b9bdc 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -62,6 +62,7 @@ export interface Action {
export interface ToastT {
id: number | string;
+ toasterId?: string;
title?: (() => React.ReactNode) | React.ReactNode;
type?: ToastTypes;
icon?: React.ReactNode;
@@ -111,6 +112,7 @@ interface ToastOptions {
unstyled?: boolean;
classNames?: ToastClassnames;
closeButtonAriaLabel?: string;
+ toasterId?: string;
}
type Offset =
@@ -124,6 +126,7 @@ type Offset =
| number;
export interface ToasterProps {
+ id?: string;
invert?: boolean;
theme?: 'light' | 'dark' | 'system';
position?: Position;
@@ -192,4 +195,5 @@ export interface ToastToDismiss {
export type ExternalToast = Omit<ToastT, 'id' | 'type' | 'title' | 'jsx' | 'delete' | 'promise'> & {
id?: number | string;
+ toasterId?: string;
};
diff --git a/test/src/app/page.tsx b/test/src/app/page.tsx
index 1511bb6..a4b603e 100644
--- a/test/src/app/page.tsx
+++ b/test/src/app/page.tsx
@@ -245,7 +245,6 @@ export default function Home({ searchParams }: any) {
>
Extended Promise Toast
</button>
-
<button
data-testid="extended-promise-error"
@@ -314,6 +313,14 @@ export default function Home({ searchParams }: any) {
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
data-testid="testid-toast-button"
className="button"
onClick={() => toast('Toast with test ID', { testId: 'my-test-toast' })}
@@ -367,6 +374,13 @@ export default function Home({ searchParams }: any) {
) : undefined,
}}
/>
+ <Toaster
+ id="secondary"
+ position="top-left"
+ toastOptions={{
+ className: 'secondary-toaster',
+ }}
+ />
</>
);
}
diff --git a/test/tests/basic.spec.ts b/test/tests/basic.spec.ts
index 69eb6e3..b8c7ed0 100644
--- a/test/tests/basic.spec.ts
+++ b/test/tests/basic.spec.ts
@@ -294,6 +294,20 @@ test.describe('Basic functionality', () => {
await expect(page.getByLabel('Yeet the notice', { exact: true })).toHaveCount(1);
});
+ test('toast with toasterId only appears in the correct Toaster', async ({ page }) => {
+ await page.getByTestId('toast-secondary').click();
+ const secondaryToaster = page.locator('[data-sonner-toaster][data-x-position="left"][data-y-position="top"]');
+ await expect(secondaryToaster.getByText('Secondary Toaster Toast')).toHaveCount(1);
+ const globalToaster = page.locator('[data-sonner-toaster][data-x-position="right"][data-y-position="bottom"]');
+ await expect(globalToaster.getByText('Secondary Toaster Toast')).toHaveCount(0);
+ });
+
+ test('toast without toasterId only appears in the global Toaster', async ({ page }) => {
+ await page.getByTestId('toast-global').click();
+ const globalToaster = page.locator('[data-sonner-toaster][data-x-position="right"][data-y-position="bottom"]');
+ await expect(globalToaster.getByText('Global Toaster Toast')).toHaveCount(1);
+ const secondaryToaster = page.locator('[data-sonner-toaster][data-x-position="left"][data-y-position="top"]');
+ await expect(secondaryToaster.getByText('Global Toaster Toast')).toHaveCount(0);
test('toast with testId renders data-testid attribute correctly', async ({ page }) => {
await page.getByTestId('testid-toast-button').click();
await expect(page.getByTestId('my-test-toast')).toBeVisible();
diff --git a/website/src/pages/toast.mdx b/website/src/pages/toast.mdx
index bd0b703..eddd997 100644
--- a/website/src/pages/toast.mdx
+++ b/website/src/pages/toast.mdx
@@ -224,6 +224,15 @@ toast(
);
```
+### Targeting a specific Toaster
+
+You can target a specific Toaster by passing a `toasterId` option:
+
+```jsx
+// This toast will only appear in the Toaster with id="canvas"
+toast('This will show in the canvas Toaster', { toasterId: 'canvas' });
+```
+
## API Reference
| Property | Description | Default |
@@ -243,4 +252,3 @@ toast(
| unstyled | Removes the default styling, which allows for easier customization. | `false` |
| actionButtonStyle | Styles for the action button | `{}` |
| cancelButtonStyle | Styles for the cancel button | `{}` |
-
diff --git a/website/src/pages/toaster.mdx b/website/src/pages/toaster.mdx
index e3835c0..a7ce93c 100644
--- a/website/src/pages/toaster.mdx
+++ b/website/src/pages/toaster.mdx
@@ -6,6 +6,22 @@ This component renders all the toasts, you can place it anywhere in your app.
You can see examples of most of the scenarios described below on the [homepage](/).
+### Multiple Toasters
+
+You can render multiple Toaster components with different ids and target toasts to each one:
+
+```jsx
+<Toaster id="global" position="top-right" />
+<Toaster id="canvas" position="bottom-left" />
+
+<button onClick={() => toast('Global toast', { toasterId: 'global' })}>
+ Show in Global Toaster
+</button>
+<button onClick={() => toast('Canvas toast', { toasterId: 'canvas' })}>
+ Show in Canvas Toaster
+</button>
+```
+
### Expand
When you hover on one of the toasts, they will expand. You can make that the default behavior by setting the `expand` prop to `true`, and customize it even further with the `visibleToasts` prop.
@@ -53,26 +69,26 @@ You can customize the default ARIA label for the notification container and the
```jsx
// example in Finnish
-<Toaster containerAriaLabel="Ilmoitukset" toastOptions={{closeButtonAriaLabel: 'Sulje'}} />
+<Toaster containerAriaLabel="Ilmoitukset" toastOptions={{ closeButtonAriaLabel: 'Sulje' }} />
```
## API Reference
-| Property | Description | Default |
-| :-------------------- | :-----------------------------------------------------------------------------------------------------------------------------: | ----------------------------------: |
-| theme | Toast's theme, either `light`, `dark`, or `system` | `light` |
-| richColors | Makes error and success state more colorful | `false` |
-| expand | Toasts will be expanded by default | `false` |
-| visibleToasts | Amount of visible toasts | `3` |
-| position | Place where the toasts will be rendered | `bottom-right` |
-| closeButton | Adds a close button to all toasts | `false` |
-| offset | Offset from the edges of the screen. | `32px` |
-| mobileOffset | Offset from the left/right edges of the screen on screens with width smaller than 600px. | `16px` |
-| dir | Directionality of toast's text | `ltr` |
-| hotkey | Keyboard shortcut that will move focus to the toaster area. | `⌥/alt + T` |
-| invert | Dark toasts in light mode and vice versa. | `false` |
-| toastOptions | These will act as default options for all toasts. See [toast()](/toast) for all available options. | `4000` |
-| gap | Gap between toasts when expanded | `14` |
-| loadingIcon | Changes the default loading icon | `-` |
-| pauseWhenPageIsHidden | Pauses toast timers when the page is hidden, e.g., when the tab is backgrounded, the browser is minimized, or the OS is locked. | `false` |
-| icons | Changes the default icons | `-` |
+| Property | Description | Default |
+| :-------------------- | :-----------------------------------------------------------------------------------------------------------------------------: | -------------: |
+| theme | Toast's theme, either `light`, `dark`, or `system` | `light` |
+| richColors | Makes error and success state more colorful | `false` |
+| expand | Toasts will be expanded by default | `false` |
+| visibleToasts | Amount of visible toasts | `3` |
+| position | Place where the toasts will be rendered | `bottom-right` |
+| closeButton | Adds a close button to all toasts | `false` |
+| offset | Offset from the edges of the screen. | `32px` |
+| mobileOffset | Offset from the left/right edges of the screen on screens with width smaller than 600px. | `16px` |
+| dir | Directionality of toast's text | `ltr` |
+| hotkey | Keyboard shortcut that will move focus to the toaster area. | `⌥/alt + T` |
+| invert | Dark toasts in light mode and vice versa. | `false` |
+| toastOptions | These will act as default options for all toasts. See [toast()](/toast) for all available options. | `4000` |
+| gap | Gap between toasts when expanded | `14` |
+| loadingIcon | Changes the default loading icon | `-` |
+| pauseWhenPageIsHidden | Pauses toast timers when the page is hidden, e.g., when the tab is backgrounded, the browser is minimized, or the OS is locked. | `false` |
+| icons | Changes the default icons | `-` |