Skip to content

Commit

Permalink
Close custom toasts
Browse files Browse the repository at this point in the history
  • Loading branch information
emilkowalski committed Nov 5, 2023
1 parent c1e0ef6 commit 667d184
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class Observer {
message?: string | React.ReactNode;
type?: ToastTypes;
promise?: PromiseT;
jsx?: React.ReactElement;
},
) => {
const { message, ...rest } = data;
Expand Down Expand Up @@ -149,10 +150,9 @@ class Observer {
return id;
};

// We can't provide the toast we just created as a prop as we didn't create it yet, so we can create a default toast object, I just don't know how to use function in argument when calling()?
custom = (jsx: (id: number | string) => React.ReactElement, data?: ExternalToast) => {
const id = data?.id || toastsCounter++;
this.publish({ jsx: jsx(id), id, ...data });
this.create({ jsx: jsx(id), id, ...data });
return id;
};
}
Expand Down
17 changes: 17 additions & 0 deletions website/src/components/Hero/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,21 @@ import { toast } from 'sonner';
import styles from './hero.module.css';
import Link from 'next/link';

export const headlessToast = (message: string) => {
toast.custom(
(t) => (
<div>
{message}
<button onClick={() => toast.dismiss(t)}>x</button>
</div>
),
{
// dismissible: true
// onDismiss: (t) => toast.dismiss(t.id)
},
);
};

export const Hero = () => {
return (
<div className={styles.wrapper}>
Expand All @@ -17,6 +32,7 @@ export const Hero = () => {
<button
data-primary=""
onClick={() => {
headlessToast('headless toast');
toast('Sonner', {
description: 'An opinionated toast component for React.',
});
Expand All @@ -25,6 +41,7 @@ export const Hero = () => {
>
Render a toast
</button>
<button onClick={() => toast.dismiss()}>dismiss all</button>
<a className={styles.button} href="https://github.com/emilkowalski/sonner" target="_blank">
GitHub
</a>
Expand Down
6 changes: 6 additions & 0 deletions website/src/pages/toast.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ const toastId = toast('Event has been created');
toast.dismiss(toastId);
```

You can also dismiss all toasts at once by calling `toast.dismiss()` without an id.

```jsx
toast.dismiss();
```

## API Reference

| Property | Description | Default |
Expand Down

0 comments on commit 667d184

Please sign in to comment.