Toaster
Installation
npx gbs-add-block@latest -a Toast
The Toasts
component is designed to display toast notifications on the screen. This documentation outlines the component's props, usage, and features.
Installation
Ensure you have a React project set up. Then, include the toast components and hooks in your project as below.
import type { Metadata } from "next";
import "./globals.css";
import { Toaster } from "path to toaster";
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`antialiased`}>
{children}
<Toaster position="top-right" />
</body>
</html>
);
}
The example is for Next.js and the Toaster can also be used in other React projects as well Usage
useToast()
Hook
Purpose:
Provides an API for adding and managing toast notifications.
Import:
import { useToast } from "./useToast";
Usage:
const { toast, dismiss, toasts } = useToast();
toast({
title: "Success",
description: "Your action was successful!",
type: "success",
duration: 5000,
});
API:
toast(props: Omit<Toast, "id">)
: Adds a toast notification.dismiss(id: string)
: Dismisses a specific toast by ID.toasts
: Array of active toast notifications.
Example
"use client";
import { useToast } from "../component-lib/toast/useToast";
export default function MyComponent() {
const { toast } = useToast();
// Basic usage remains the same
const showBasicToast = () => {
toast({
title: "Success!",
description: "Action completed.",
type: "success",
});
};
// Custom JSX content
const showCustomToast = () => {
toast({
content: (
<div className="bg-white rounded-lg p-4 shadow-lg border">
<div className="flex items-center gap-3">
<img
src="/next.svg"
alt="User"
className="w-10 h-10 rounded-full"
/>
<div>
<h4 className="font-semibold">New Message</h4>
<p className="text-sm text-gray-500">
You have a new message from John
</p>
</div>
</div>
<div className="mt-3 flex gap-2">
<button className="px-3 py-1 bg-blue-500 text-white rounded-md">
View
</button>
<button className="px-3 py-1 bg-gray-200 rounded-md">
Dismiss
</button>
</div>
</div>
),
duration: 8000,
});
};
return (
<div>
<button onClick={showBasicToast}>Show Basic Toast</button>
<button onClick={showCustomToast}>Show Custom Toast</button>
</div>
);
}
Toast Configuration
Each toast notification supports the following properties:
Property
Type
Description
id
string
Unique identifier (auto-generated).
title
string
The title of the toast.
description
string
A short description message.
type
string
"default", "success", "error", or "warning".
duration
number
Duration in milliseconds before auto-dismissal.
content
ReactNode
Custom JSX content (optional).
This pure React toast system is lightweight, simple, and easy to integrate into any project. Modify the useToastStore
implementation as needed to fit different state management patterns.
Last updated