Skip to content

An opinionated toast component for React.

Add onDismiss and onAutoClose callbacks (#52)

Emil Kowalskie81cb77a3478
diff --git a/README.md b/README.md
index 745a7c9..f5040f6 100644
--- a/README.md
+++ b/README.md
@@ -234,6 +234,17 @@ toast('Event has been created', {
});
```
+### On Close Callback
+
+You can pass `onDismiss` and `onAutoClose` callbacks. `onDismiss` gets fired when either the close button gets clicked or the toast is swiped. `onAutoClose` fires when the toast disappears automatically after it's timeout (`duration` prop).
+
+```jsx
+toast('Event has been created', {
+ onDismiss: (t) => console.log(`Toast with id ${t.id} has been dismissed`),
+ onAutoClose: (t) => console.log(`Toast with id ${t.id} has been closed automatically`),
+});
+```
+
## Keyboard focus
You can focus on the toast area by pressing ⌥/alt + T. You can override it by providing an array of event.code values for each key.
diff --git a/src/index.tsx b/src/index.tsx
index 9333d9b..718cd04 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -176,6 +176,7 @@ const Toast = (props: ToastProps) => {
closeTimerStartTimeRef.current = new Date().getTime();
// Let the toast know it has started
timeoutId = setTimeout(() => {
+ toast.onAutoClose?.(toast);
deleteToast();
}, closeTimerRemainingTimeRef.current);
};
@@ -273,6 +274,7 @@ const Toast = (props: ToastProps) => {
// Remove only if treshold is met
if (Math.abs(swipeAmount) >= SWIPE_TRESHOLD) {
setOffsetBeforeRemove(offset.current);
+ toast.onDismiss?.(toast);
deleteToast();
setSwipeOut(true);
return;
@@ -302,7 +304,14 @@ const Toast = (props: ToastProps) => {
aria-label="Close toast"
data-disabled={disabled}
data-close-button
- onClick={disabled ? undefined : deleteToast}
+ onClick={
+ disabled
+ ? undefined
+ : () => {
+ deleteToast();
+ toast.onDismiss?.(toast);
+ }
+ }
>
<svg
xmlns="http://www.w3.org/2000/svg"
diff --git a/src/types.ts b/src/types.ts
index 305d0f5..dbe3392 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -29,6 +29,8 @@ export interface ToastT {
label: string;
onClick?: () => void;
};
+ onDismiss?: (toast: ToastT) => void;
+ onAutoClose?: (toast: ToastT) => void;
promise?: PromiseT;
style?: React.CSSProperties;
className?: string;
diff --git a/test/src/app/page.tsx b/test/src/app/page.tsx
index 0cd05db..3a65a19 100644
--- a/test/src/app/page.tsx
+++ b/test/src/app/page.tsx
@@ -1,10 +1,14 @@
'use client';
+import React from 'react';
import { Toaster, toast } from 'sonner';
const promise = () => new Promise((resolve) => setTimeout(resolve, 2000));
export default function Home() {
+ const [showAutoClose, setShowAutoClose] = React.useState(false);
+ const [showDismiss, setShowDismiss] = React.useState(false);
+
return (
<>
<h1>tests</h1>
@@ -61,6 +65,30 @@ export default function Home() {
<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),
+ })
+ }
+ >
+ Render Toast With onAutoClose callback
+ </button>
+ {showAutoClose ? <div data-testid="auto-close-el" /> : null}
+ {showDismiss ? <div data-testid="dismiss-el" /> : null}
<Toaster />
</>
);
diff --git a/test/tests/basic.spec.ts b/test/tests/basic.spec.ts
index 7d1d956..97ae51b 100644
--- a/test/tests/basic.spec.ts
+++ b/test/tests/basic.spec.ts
@@ -57,4 +57,18 @@ test.describe('Basic functionality', () => {
await timeout;
await expect(page.locator('[data-sonner-toast]')).toHaveCount(1);
});
+
+ test("toast's auto close callback gets executed correctly", async ({ page }) => {
+ await page.getByTestId('auto-close-toast-callback').click();
+ await expect(page.getByTestId('auto-close-el')).toHaveCount(1);
+ });
+
+ test("toast's dismiss callback gets executed correctly", async ({ page }) => {
+ await page.getByTestId('dismiss-toast-callback').click();
+ await page.hover('[data-sonner-toast]');
+ await page.mouse.down();
+ await page.mouse.move(0, 800);
+ await page.mouse.up();
+ await expect(page.getByTestId('dismiss-el')).toHaveCount(1);
+ });
});
diff --git a/website/src/components/Hero/index.tsx b/website/src/components/Hero/index.tsx
index 28c77b9..d9824a7 100644
--- a/website/src/components/Hero/index.tsx
+++ b/website/src/components/Hero/index.tsx
@@ -19,6 +19,10 @@ export const Hero = () => {
toast('Sonner', {
description: 'An opinionated toast component for React.',
});
+ toast('Event has been created', {
+ onDismiss: (t) => console.log(`Toast with id ${t.id} has been dismissed`),
+ onAutoClose: (t) => console.log(`Toast with id ${t.id} has been closed automatically`),
+ });
}}
className={styles.button}
>