GitHub

Toast

Displays a message to the user in a toast.

toast-demo.tsx
"use client"
 
import { useToast } from "@/hooks/use-toast"
 
import { Button } from "@/components/ui/button"
 
export function ToastDemo() {
	const toast = useToast()
 
	return (
		<Button
			onClick={() =>
				toast.add({
					title: "Your request has been sent",
					description: "We'll get back to you as soon as possible",
				})
			}
		>
			Show Toast
		</Button>
	)
}

Installation

Run the following command.

npx shadcn@latest add @9ui/toast

Add ToastProvider to your app layout.

app/layout.tsx
import { ToastProvider } from "@/components/ui/toast"
 
export default function RootLayout({ children }) {
	return (
		<html lang="en">
			<head />
			<body>
				<ToastProvider>
					<main>{children}</main>
				</ToastProvider>
			</body>
		</html>
	)
}

Examples

Promise

toast-promise.tsx
"use client"
 
import { useToast } from "@/hooks/use-toast"
 
import { Button } from "@/components/ui/button"
 
export function ToastPromiseDemo() {
	const toast = useToast()
 
	return (
		<Button
			onClick={() =>
				toast.promise(
					new Promise<string>((resolve) => {
						setTimeout(() => {
							resolve("Request sent")
						}, 2000)
					}),
					{
						loading: "Sending request...",
						success: (data: string) => `Success: ${data}`,
						error: (err: Error) => `Error: ${err.message}`,
					}
				)
			}
		>
			Show Toast
		</Button>
	)
}

Action

toast-action.tsx
"use client"
 
import { useToast } from "@/hooks/use-toast"
 
import { Button } from "@/components/ui/button"
 
export function ToastActionDemo() {
	const toast = useToast()
 
	return (
		<Button
			onClick={() => {
				const id = toast.add({
					title: "Your email has been sent",
					description: "We'll get back to you as soon as possible",
					actionProps: {
						children: "Unsend",
						onClick: () => {
							toast.close(id)
							toast.add({
								title: "Email unsent",
								type: "success",
							})
						},
					},
				})
			}}
		>
			Show Toast
		</Button>
	)
}

Rich Colors

toast-rich-colors.tsx
"use client"
 
import { useToast } from "@/hooks/use-toast"
 
import { Button } from "@/components/ui/button"
 
export function ToastRichColorsDemo() {
	const toast = useToast()
 
	return (
		<div className="grid grid-cols-2 gap-2">
			<Button
				onClick={() =>
					toast.add({
						title: "Success",
						type: "success",
					})
				}
			>
				success
			</Button>
			<Button
				onClick={() =>
					toast.add({
						title: "Error",
						type: "error",
					})
				}
			>
				error
			</Button>
			<Button
				onClick={() =>
					toast.add({
						title: "Warning",
						type: "warning",
					})
				}
			>
				warning
			</Button>
			<Button
				onClick={() =>
					toast.add({
						title: "Info",
						type: "info",
					})
				}
			>
				info
			</Button>
		</div>
	)
}