### Install Sonner using npm
Source: https://github.com/emilkowalski/sonner/blob/main/README.md
This command installs the Sonner library into your React project using npm. Ensure you have Node.js and npm installed.
```bash
npm install sonner
```
--------------------------------
### Install Sonner Package
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/getting-started.mdx
Install the Sonner library using various package managers. Choose the command corresponding to your project's environment.
```bash
pnpm i sonner
```
```bash
npm i sonner
```
```bash
yarn add sonner
```
```bash
bun add sonner
```
--------------------------------
### Installation
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/getting-started.mdx
Install Sonner using your preferred package manager.
```APIDOC
## Installation
Sonner can be installed using various package managers.
### pnpm
```bash
pnpm i sonner
```
### npm
```bash
npm i sonner
```
### yarn
```bash
yarn add sonner
```
### bun
```bash
bun add sonner
```
```
--------------------------------
### Showing Info Toasts with `toast.info()`
Source: https://context7.com/emilkowalski/sonner/llms.txt
Utilize `toast.info()` for general informational messages or neutral notifications. This function displays an info icon and supports an `action` object for adding clickable buttons within the toast, as shown in the example for a 'Learn more' link.
```tsx
import { toast } from 'sonner';
function InfoExample() {
const showInfo = () => {
toast.info('New feature available', {
description: 'Check out our new dashboard settings',
action: {
label: 'Learn more',
onClick: () => window.open('/docs/new-features'),
},
});
};
return ;
}
```
--------------------------------
### Creating Success Toasts with `toast.success()`
Source: https://context7.com/emilkowalski/sonner/llms.txt
Use `toast.success()` to display a notification confirming a successful operation. This function automatically includes a success checkmark icon. The example demonstrates its use within an asynchronous function, handling potential errors with `toast.error()`.
```tsx
import { toast } from 'sonner';
function SaveButton() {
const handleSave = async () => {
try {
await saveData();
toast.success('Changes saved successfully', {
description: 'Your profile has been updated',
duration: 3000,
});
} catch (error) {
toast.error('Failed to save changes');
}
};
return ;
}
```
--------------------------------
### Render a Toast Notification
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/getting-started.mdx
Trigger a toast notification by importing the toast function and calling it within your component logic. This example demonstrates a basic toast triggered by a button click.
```tsx
import { toast } from 'sonner';
function MyToast() {
return ;
}
```
--------------------------------
### Setting up the Toaster Component in React Layout
Source: https://context7.com/emilkowalski/sonner/llms.txt
The Toaster component acts as the container for all toast notifications. It should be placed once in your application's root layout file. This example demonstrates various props for configuring default toast behavior, such as position, theme, duration, and styling.
```tsx
import { Toaster } from 'sonner';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Displaying Basic and Optioned Toasts with `toast()`
Source: https://context7.com/emilkowalski/sonner/llms.txt
The `toast()` function is used to display notifications from anywhere in your React application. It accepts a message string and an optional options object for customization. The function returns a toast ID for programmatic control. This example shows a simple toast and one with extended options.
```tsx
import { toast } from 'sonner';
function MyComponent() {
const showToast = () => {
// Simple toast with just a message
toast('Event has been created');
// Toast with options
toast('Event has been created', {
description: 'Monday, January 3rd at 6:00pm',
duration: 5000,
icon: '📅',
position: 'top-center',
className: 'my-custom-toast',
style: { background: '#333', color: '#fff' },
});
};
return ;
}
// Toast on page load (must be in setTimeout or requestAnimationFrame)
setTimeout(() => {
toast('Welcome back!');
});
```
--------------------------------
### Displaying Error Toasts with `toast.error()`
Source: https://context7.com/emilkowalski/sonner/llms.txt
The `toast.error()` function is used to notify users of failures or errors. It displays a distinct error icon. This example shows how to catch errors from an asynchronous operation and present an informative error message, including dynamic error details.
```tsx
import { toast } from 'sonner';
function DeleteButton() {
const handleDelete = async () => {
try {
await deleteItem();
toast.success('Item deleted');
} catch (error) {
toast.error('Failed to delete item', {
description: error.message || 'Please try again later',
duration: 5000,
});
}
};
return ;
}
```
--------------------------------
### Render Basic Toast Notifications
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Demonstrates how to trigger a simple toast notification using a string or an options object for further customization like duration and icons.
```jsx
import { toast } from 'sonner';
toast('Hello World!');
toast('My toast', {
className: 'my-classname',
description: 'My description',
duration: 5000,
icon: ,
});
```
--------------------------------
### Basic Sonner Usage in React
Source: https://github.com/emilkowalski/sonner/blob/main/README.md
Demonstrates how to integrate Sonner into a React application. It shows importing the Toaster component and the toast function, rendering the Toaster, and triggering a simple toast message on a button click.
```jsx
import { Toaster, toast } from 'sonner';
// ...
function App() {
return (
);
}
```
--------------------------------
### Configure Multiple Toaster Instances
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toaster.mdx
Demonstrates how to render multiple Toaster components with unique IDs and target specific toasts to them using the toasterId property.
```jsx
```
--------------------------------
### Custom Element Rendering
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Demonstrates how to render custom JSX elements, including links and buttons, within toast titles and descriptions.
```APIDOC
## Rendering custom elements
You can render custom elements inside the toast like `` or custom components by passing a function instead of a string. This work for both the title and description.
### Request Example
```jsx
tost(
() => (
<>
View{' '}
Animation on the Web
>
),
{
description: () => ,
},
);
```
```
--------------------------------
### Status-Specific Toasts
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Shows how to use built-in methods for success, error, and loading states to provide immediate visual feedback to the user.
```jsx
toast.success('My success toast');
toast.error('My error toast');
toast.loading('Loading data');
```
--------------------------------
### Custom and Headless Toasts
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Explains how to render custom JSX content within a toast, either maintaining default styles or using a fully headless approach for complete control.
```jsx
toast(
A custom toast with default styling
, { duration: 5000 });
toast.custom((t) => (
This is a custom component
));
```
--------------------------------
### Handle Promises with Toasts
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Demonstrates how to automatically update a toast based on the resolution or rejection of a promise, including custom success/error message formatting.
```jsx
toast.promise(myPromise, {
loading: 'Loading...',
success: (data) => `${data.name} toast has been added`,
error: 'Error',
});
```
--------------------------------
### Toast API Reference
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Detailed reference for the properties available when creating a toast, including descriptions, defaults, and types.
```APIDOC
## API Reference
| Property | Description | Default |
| :---------------- | :----------------------------------------------------------------------------------------------------: | -------------: |
| description | Toast's description, renders underneath the title. | `-` |
| closeButton | Adds a close button. | `false` |
| invert | Dark toast in light mode and vice versa. | `false` |
| duration | Time in milliseconds that should elapse before automatically closing the toast. | `4000` |
| position | Position of the toast. | `bottom-right` |
| dismissible | If `false`, it'll prevent the user from dismissing the toast. | `true` |
| icon | Icon displayed in front of toast's text, aligned vertically. | `-` |
| action | Renders a primary button, clicking it will close the toast. | `-` |
| cancel | Renders a secondary button, clicking it will close the toast. | `-` |
| id | Custom id for the toast. | `-` |
| onDismiss | The function gets called when either the close button is clicked, or the toast is swiped. | `-` |
| onAutoClose | Function that gets called when the toast disappears automatically after it's timeout (duration` prop). | `-` |
| unstyled | Removes the default styling, which allows for easier customization. | `false` |
| actionButtonStyle | Styles for the action button | `{}` |
| cancelButtonStyle | Styles for the cancel button | `{}` |
```
--------------------------------
### Render a toast
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/getting-started.mdx
Render a toast message using the `toast` function.
```APIDOC
## Render a toast
Use the `toast` function to display a toast message.
### Usage
```tsx
import { toast } from 'sonner';
function MyToast() {
return ;
}
```
```
--------------------------------
### Implement Multiple Toasters with Sonner
Source: https://context7.com/emilkowalski/sonner/llms.txt
Demonstrates how to render multiple `Toaster` components with unique IDs to manage toasts in different locations or with distinct configurations. Toasts can be targeted to specific toasters using the `toasterId` option.
```tsx
import { Toaster, toast } from 'sonner';
function App() {
return (
<>
>
);
}
```
--------------------------------
### Add Actions and Cancel Buttons
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Shows how to add interactive action or cancel buttons to a toast, supporting both object configurations and custom JSX components.
```jsx
toast('My action toast', {
action: {
label: 'Action',
onClick: () => console.log('Action!'),
},
});
toast('My cancel toast', {
cancel: ,
});
```
--------------------------------
### Manage Toast Lifecycle and Positioning
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Covers advanced management techniques including updating existing toasts, setting dynamic positions, handling dismissal callbacks, and programmatically removing toasts.
```jsx
const toastId = toast('Sonner');
toast.success('Toast has been updated', { id: toastId });
toast('Hello World', { position: 'top-center' });
toast.dismiss(toastId);
```
--------------------------------
### Customize Toaster Expansion and Visibility
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toaster.mdx
Configures the Toaster to expand on hover by default and sets the maximum number of visible toasts simultaneously.
```jsx
```
--------------------------------
### Add Toaster to your app
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/getting-started.mdx
Add the Toaster component to your application's root layout.
```APIDOC
## Add Toaster to your app
It can be placed anywhere, even in server components such as `layout.tsx`.
### Setup
```tsx
import { Toaster } from 'sonner';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
```
--------------------------------
### Display Loading Toast
Source: https://context7.com/emilkowalski/sonner/llms.txt
Displays a toast with a loading spinner. This allows for manual control over the toast state during asynchronous operations like file uploads.
```tsx
import { toast } from 'sonner';
function UploadButton() {
const handleUpload = async (file: File) => {
const toastId = toast.loading('Uploading file...');
try {
const result = await uploadFile(file);
toast.success('File uploaded successfully', { id: toastId });
} catch (error) {
toast.error('Upload failed', { id: toastId });
}
};
return handleUpload(e.target.files[0])} />;
}
```
--------------------------------
### Render Custom JSX and Headless Toasts with Sonner
Source: https://context7.com/emilkowalski/sonner/llms.txt
Demonstrates how to render custom JSX content directly within toasts or create fully custom, headless toast components. This allows for rich, interactive toast UIs while maintaining Sonner's core functionality and styling.
```tsx
import { toast } from 'sonner';
function CustomToastExample() {
// Custom JSX with default styling
const showCustom = () => {
toast(
));
};
return (
<>
>
);
}
```
--------------------------------
### Render Custom Elements in Toasts
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Demonstrates how to pass a function that returns JSX to the toast title or description properties. This allows for the inclusion of interactive elements like links and buttons within the notification.
```jsx
toast(
() => (
<>
View{' '}
Animation on the Web
>
),
{
description: () => ,
}
);
```
--------------------------------
### Targeting a Specific Toaster
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Explains how to direct a toast message to a particular toaster instance by specifying its unique ID.
```APIDOC
## Targeting a specific Toaster
You can target a specific Toaster by passing a `toasterId` option:
### Request Example
```jsx
// This toast will only appear in the Toaster with id="canvas"
tost('This will show in the canvas Toaster', { toasterId: 'canvas' });
```
```
--------------------------------
### Display Promise Toast
Source: https://context7.com/emilkowalski/sonner/llms.txt
Automatically manages toast states based on a promise resolution or rejection. It transitions from loading to success or error states automatically.
```tsx
import { toast } from 'sonner';
function FetchDataButton() {
const fetchData = () => {
const promise = fetch('/api/data').then((res) => {
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
});
toast.promise(promise, {
loading: 'Loading data...',
success: (data) => `Loaded ${data.items.length} items`,
error: (err) => `Error: ${err.message}`,
finally: () => console.log('Request completed'),
});
};
return ;
}
```
--------------------------------
### Global Toast Styling with toastOptions
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/styling.mdx
Apply consistent styling to all toasts by configuring `toastOptions` on the `Toaster` component. This affects background, class names, and other style properties globally.
```jsx
```
--------------------------------
### Apply Global Toast Styles
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toaster.mdx
Uses the toastOptions prop to apply default styles and CSS classes to all toasts rendered within the Toaster container.
```jsx
```
--------------------------------
### Handle Toast Lifecycle Events with Callbacks in Sonner
Source: https://context7.com/emilkowalski/sonner/llms.txt
Explains how to use `onDismiss` and `onAutoClose` callbacks to react to toast lifecycle events. `onDismiss` is triggered by user interaction, while `onAutoClose` fires when the toast disappears due to its duration expiring.
```tsx
import { toast } from 'sonner';
function CallbackExample() {
const showWithCallbacks = () => {
toast('Important notification', {
duration: 5000,
onDismiss: (t) => {
console.log(`Toast ${t.id} was dismissed by user`);
trackEvent('toast_dismissed', { toastId: t.id });
},
onAutoClose: (t) => {
console.log(`Toast ${t.id} auto-closed`);
trackEvent('toast_auto_closed', { toastId: t.id });
},
});
};
return ;
}
```
--------------------------------
### Trigger Toasts on Page Load
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Explains the requirement to wrap the toast function in a setTimeout or requestAnimationFrame to ensure it triggers correctly during the initial page load.
```jsx
setTimeout(() => {
toast('My toast on a page load');
});
```
--------------------------------
### Configure Custom ARIA Labels
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toaster.mdx
Provides localized or custom ARIA labels for the notification container and the toast close button to improve accessibility.
```jsx
```
--------------------------------
### Individual Toast Styling
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/styling.mdx
Style a specific toast by passing style options directly when calling the `toast` function. This allows for unique styling on a per-toast basis, overriding global settings.
```jsx
toast('Hello World', {
style: {
background: 'red',
},
className: 'class',
});
```
--------------------------------
### Target a Specific Toaster
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toast.mdx
Shows how to route a toast notification to a specific Toaster component instance by providing a toasterId option. This is useful for managing multiple toast containers on a single page.
```javascript
toast('This will show in the canvas Toaster', { toasterId: 'canvas' });
```
--------------------------------
### Display Toast with Action Button
Source: https://context7.com/emilkowalski/sonner/llms.txt
Adds a primary action button to a toast notification. This is useful for providing immediate user feedback or undo functionality.
```tsx
import { toast } from 'sonner';
function UndoExample() {
const deleteItem = (itemId: string) => {
removeFromList(itemId);
toast('Item deleted', {
description: 'The item has been removed from your list',
action: {
label: 'Undo',
onClick: () => {
restoreItem(itemId);
toast.success('Item restored');
},
},
duration: 5000,
});
};
return ;
}
```
--------------------------------
### Integrate Toaster Component
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/getting-started.mdx
Add the Toaster component to your root layout to enable toast rendering across your application. It can be placed in server components like layout.tsx.
```tsx
import { Toaster } from 'sonner';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Update Existing Toasts in Sonner
Source: https://context7.com/emilkowalski/sonner/llms.txt
Illustrates how to update the content or options of an existing toast by providing its ID in a subsequent toast call. This is ideal for showing loading states, progress updates, or changing toast messages dynamically.
```tsx
import { toast } from 'sonner';
function UpdateExample() {
const processWithUpdates = async () => {
const toastId = toast.loading('Starting process...');
// Update progress
await step1();
toast.loading('Step 1 complete, processing step 2...', { id: toastId });
await step2();
toast.loading('Almost done...', { id: toastId });
await step3();
toast.success('Process completed!', {
id: toastId,
description: 'All steps finished successfully',
});
};
return ;
}
```
--------------------------------
### Style Toasts with Tailwind CSS
Source: https://context7.com/emilkowalski/sonner/llms.txt
Use the unstyled prop combined with classNames to override default styles. This allows for full customization of toast components using Tailwind utility classes globally or per-toast.
```tsx
import { Toaster, toast } from 'sonner';
// Global styling via Toaster
function App() {
return (
);
}
// Per-toast styling
toast.success('Styled toast', {
unstyled: true,
classNames: {
toast: 'bg-green-50 border border-green-200 rounded-xl p-4',
title: 'text-green-800 font-semibold',
description: 'text-green-600',
},
});
```
--------------------------------
### Programmatically Dismiss Toasts with Sonner
Source: https://context7.com/emilkowalski/sonner/llms.txt
Shows how to dismiss specific toasts using their unique IDs or dismiss all active toasts at once. This is useful for managing toast lifecycles based on user actions or application state.
```tsx
import { toast } from 'sonner';
function DismissExample() {
let toastId: string | number;
const showPersistent = () => {
toastId = toast('This toast stays until dismissed', {
duration: Infinity,
dismissible: false, // Prevent swipe/click to dismiss
});
};
const dismissToast = () => {
toast.dismiss(toastId); // Dismiss specific toast
};
const dismissAll = () => {
toast.dismiss(); // Dismiss all toasts
};
return (
<>
>
);
}
```
--------------------------------
### Manage Toasts with useSonner Hook
Source: https://context7.com/emilkowalski/sonner/llms.txt
The useSonner hook provides reactive access to the current list of active toasts. This is useful for building custom notification management interfaces.
```tsx
import { useSonner, toast } from 'sonner';
function ToastManager() {
const { toasts } = useSonner();
return (
Active Toasts: {toasts.length}
{toasts.map((t) => (
{t.title} - {t.type}
))}
);
}
```
--------------------------------
### Customizing Default Icons
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/styling.mdx
Replace the default icons for different toast types (success, info, warning, error, loading) by providing custom React components via the `icons` prop on the `Toaster` component.
```jsx
,
info: ,
warning: ,
error: ,
loading: ,
}}
/>
```
--------------------------------
### Retrieve Toast History and Active Toasts
Source: https://context7.com/emilkowalski/sonner/llms.txt
Access historical and currently visible toast data using static methods. Useful for debugging or building analytics dashboards for notifications.
```tsx
import { toast } from 'sonner';
function ToastDebugger() {
const showStats = () => {
const history = toast.getHistory(); // All toasts ever created
const active = toast.getToasts(); // Currently visible toasts
console.log(`Total toasts: ${history.length}`);
console.log(`Active toasts: ${active.length}`);
console.log('Active:', active.map(t => ({ id: t.id, title: t.title })));
};
return ;
}
```
--------------------------------
### Setting Individual Toast Icons
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/styling.mdx
Assign a custom icon to a specific toast by passing a React component to the `icon` prop when calling the `toast()` function. This allows for unique icons on a per-toast basis.
```jsx
toast('Hello World', {
icon: ,
});
```
--------------------------------
### Individual Tailwind CSS Styling with toast()
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/styling.mdx
Apply Tailwind CSS classes to individual toasts by passing `unstyled: true` and `classNames` directly to the `toast()` function. This provides granular control over the appearance of specific toasts.
```jsx
toast('Hello World', {
unstyled: true,
classNames: {
toast: 'bg-blue-400',
title: 'text-red-400 text-2xl',
description: 'text-red-400',
actionButton: 'bg-zinc-400',
cancelButton: 'bg-orange-400',
closeButton: 'bg-lime-400',
},
});
```
--------------------------------
### Styling Toasts by Type with Tailwind CSS
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/styling.mdx
Customize the appearance of different toast types (error, success, warning, info) using Tailwind CSS by specifying type-specific class names within `toastOptions.classNames`.
```jsx
```
--------------------------------
### Set Toaster Position
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toaster.mdx
Defines the screen location where toasts will be rendered. Supported values include top-left, top-center, top-right, bottom-left, bottom-center, and bottom-right.
```jsx
```
--------------------------------
### Display Toast with Cancel Button
Source: https://context7.com/emilkowalski/sonner/llms.txt
Adds a secondary cancel button to the toast. This is typically used for confirmation dialogs where the user needs to explicitly accept or decline an action.
```tsx
import { toast } from 'sonner';
function ConfirmExample() {
const confirmAction = () => {
toast('Are you sure you want to proceed?', {
action: {
label: 'Confirm',
onClick: () => performAction(),
},
cancel: {
label: 'Cancel',
onClick: () => console.log('Cancelled'),
},
duration: Infinity,
});
};
return ;
}
```
--------------------------------
### Tailwind CSS Styling with unstyled prop
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/styling.mdx
Integrate Tailwind CSS for toast styling by setting `unstyled: true` in `toastOptions`. This enables custom styling through `classNames` for various toast elements.
```jsx
```
--------------------------------
### Set Text Directionality
Source: https://github.com/emilkowalski/sonner/blob/main/website/src/pages/toaster.mdx
Configures the directionality of the toast text. Supports rtl (right-to-left), ltr (left-to-right), and auto modes.
```jsx
```
--------------------------------
### Customize Toast Icons
Source: https://context7.com/emilkowalski/sonner/llms.txt
Replace default icons globally via the Toaster component or individually per-toast using the icon option. Supports React nodes or simple emoji strings.
```tsx
import { Toaster, toast } from 'sonner';
import { CheckCircle, XCircle, AlertTriangle, Info, Loader } from 'lucide-react';
// Global custom icons
function App() {
return (
,
error: ,
warning: ,
info: ,
loading: ,
}}
/>
);
}
// Per-toast icon
toast('Custom icon toast', {
icon: '🎉',
});
toast.success('With emoji icon', {
icon: '✅',
});
```
--------------------------------
### Display Warning Toast
Source: https://context7.com/emilkowalski/sonner/llms.txt
Displays a toast notification with a warning icon. This is ideal for non-critical alerts, deprecation notices, or session-related warnings.
```tsx
import { toast } from 'sonner';
function WarningExample() {
const showWarning = () => {
toast.warning('Session expiring soon', {
description: 'Your session will expire in 5 minutes',
duration: 10000,
action: {
label: 'Extend',
onClick: () => extendSession(),
},
});
};
return ;
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.