Toast

Use toast() to create a notification from anywhere in your React application

⚠️ Make sure you add the <Toaster /> provider to your app first.

tsx
import { toast } from "@pheralb/toast";
 
toast.default({
  text: `Hello ✨`,
});

toast.variant

Show a toast with a specific variant:

tsx

toast.variant with action

Show a button and execute a custom function when clicked. The default text for the button is Action:

tsx
toast.default({
  text: `A toast with 👀 action button`,
  action: {
    content: "Action", // Button label
    onClick: () => {
      // Do something
    },
  },
});

toast.loading

Show a toast with loading state and will update automatically after the promise resolves or fails:

tsx
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:

tsx
// 📃 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!
    },
  },
});

Custom Icon

You can use a custom icon for the toast using icon property:

tsx
toast.default({
  text: "Party popper!",
  icon: <PartyPopperIcon width={18} height={18} />,
});

API Reference

The toast.variant function accepts the following options:

PropertyDescriptionTypeRequired
textNotification titlestring
descriptionToast's descriptionstring-
iconIcon to display in the toastReactNode-
delayDurationDuration before the toast disappearsnumber (default: 4000)-
variantVariant of the toastVariant: info, success, warning, error or loading-
themeTheme of the toastTheme (default: system): light, dark or system-
actionShow a Action button and execute a functionlabel (default text: action) & onClick: () => void or Promise<void>-