π‘ Make sure you add the
<Toaster />
provider to your app first.
- Import the
toast
function:
import { toast } from '@pheralb/toast';
- Render a toast:
toast.variant
: Show a toast with a specific variant:
toast.variant
withaction
: Show a Action button and execute a custom function when clicked:
toast.default({
text: `A toast with π action button`,
action: {
label: 'Action', // Button label
onClick: () => {
// Do something
},
},
});
toast.loading
: Show a toast with loading state and will update automatically after the promise resolves or fails:
toast.loading({
// Initial message:
text: 'Loading',
options: {
promise: yourFunction(),
success: 'Ready',
error: 'Error',
// Close toast automatically (the duration depends by delayDuration property):
autoDismiss: true,
// Optional:
onSuccess: () => {
console.log('Success');
},
// Optional:
onError: () => {
console.log('Error');
},
},
});
β¨ For example, you can use Next.js Server Actions to show a loading toast while fetching data from an API:
// π actions/testAction.ts
'use server';
export const testAction = async (name: string) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return {
name: `Hello, ${name}!`,
};
};
// π components/Example.tsx
import { testAction } from '@/actions/testAction';
import { toast } from '@pheralb/toast';
toast.loading({
text: 'Getting data',
options: {
promise: testAction(),
success: 'Ready',
error: 'Error',
autoDismiss: false,
onSuccess: (data) => {
console.log(`Success: ${data.name}`);
// Success: Hello, pheralb!
},
},
});
API Reference
The toast.variant
function accepts the following options:
Property | Description | Type | Required |
---|---|---|---|
text | Notification title | string | β |
description | Toastβs description | string | - |
icon | Icon to display in the toast | ReactNode | - |
delayDuration | Duration before the toast disappears | number (default: 4000 ) | - |
theme | Theme of the toast | Theme (default: system ): light , dark or system | - |
action | Show a Action button and execute a function | label (default text: action ) & onClick : () => void or Promise<void> | - |