sonner is a very popular open-source library used to implement elegant and user-friendly toast notifications (brief pop-up messages such as success, error, warning notifications, etc.). It’s an “opinionated” React component library, meaning it provides a set of default styles and behaviors while also allowing developers to customize according to their needs. Below is a detailed explanation of sonner, including its core concepts, usage methods, features, and practical application knowledge points.
1. What is sonner?
sonner is a toast notification component library designed specifically for React, developed by Emil Kowalski. It aims to provide a simple, intuitive way to display notifications in React applications. Compared to other similar libraries (such as react-toastify), sonner is characterized by:
- Ready to use out of the box: Beautiful default styles, smooth animations, usable without additional configuration.
- Lightweight: Small code size, excellent performance.
- Clean API: No need for complex contexts or hooks, just import and call.
- Highly customizable: Supports various notification types and custom styles.
Its core component is <Toaster />, used to render all toast notifications, while the toast function is the entry point for triggering notifications.
2. Installation and Basic Usage
To use sonner in a React project, you need to install it first. This can be done via npm or yarn:
npm install sonner
# or
yarn add sonner
After installation, you need to import <Toaster /> in your application’s root component, and then use the toast function anywhere to trigger notifications. Here’s a basic example:
import { Toaster, toast } from 'sonner';
function App() {
return (
<div>
<Toaster />
<button onClick={() => toast('Hello, this is a toast!')}>
Show Toast
</button>
</div>
);
}
export default App;
<Toaster />: This is the container for notifications, responsible for rendering all toast messages. It’s typically placed in the top-level component of your application.toast('message'): Calling this function displays a simple toast notification, by default shown in the bottom right corner of the screen.
After running this code, clicking the button will pop up a notification with “Hello, this is a toast!” with a default fade-in and fade-out animation.
3. Core Features and Key Points
sonner provides rich functionality. Here are its main features and how to use them:
3.1 Notification Types
sonner supports multiple predefined notification types, suitable for different scenarios:
- Default notification:
toast('message') - Success notification:
toast.success('Operation successful') - Error notification:
toast.error('Something went wrong') - Info notification:
toast.info('This is a tip') - Warning notification:
toast.warning('Attention!') - Loading state:
toast.loading('Loading...')
Example:
<button onClick={() => toast.success('Task completed!')}>
Show Success Toast
</button>
<button onClick={() => toast.error('Task failed!')}>
Show Error Toast
</button>
Each type has default icons and colors (e.g., success is green, error is red), and these styles can be adjusted through configuration.
3.2 Custom Options
The toast function accepts a second parameter, an object, to customize the behavior and appearance of notifications:
toast('Event created', {
description: 'April 7, 2025 at 7:00 PM', // Additional description
duration: 5000, // Display duration (milliseconds), default is 4000
position: 'top-center', // Position: top-left, top-center, top-right, bottom-left, bottom-center, bottom-right
icon: <CustomIcon />, // Custom icon
style: { background: '#f0f0f0' }, // Custom style
className: 'my-toast', // Custom CSS class
});
3.3 Promise Support
sonner provides a powerful toast.promise API for handling notification states of asynchronous operations. For example:
toast.promise(
fetch('https://api.example.com/data'), // Promise
{
loading: 'Loading data...',
success: 'Data loaded successfully!',
error: 'Failed to load, please try again.',
}
);
When the Promise is in a pending state, it displays “Loading data…”, on success it shows “Data loaded successfully!”, and on failure it shows “Failed to load, please try again.” This is particularly suitable for network requests or form submissions.
3.4 Custom Components
You can create completely custom notification content using toast.custom:
toast.custom((t) => (
<div>
<p>This is a custom notification</p>
<button onClick={() => toast.dismiss(t)}>Close</button>
</div>
));
Here, t is the toast ID, which can be used to manually close a specific notification.
3.5 Global Configuration for <Toaster />
The <Toaster /> component supports global configuration, affecting the behavior of all toasts:
<Toaster
position="top-right" // Default position
theme="dark" // Theme: light, dark, system
richColors // Enable more vibrant colors
expand={true} // Expand all notifications by default
visibleToasts={3} // Number of notifications visible at once
closeButton // Show close button
toastOptions={{
style: { fontFamily: 'Arial' }, // Global style
}}
/>
4. Advanced Usage
4.1 Manually Closing Notifications
Each toast has a unique ID that can be used to close it manually:
const toastId = toast('This is a notification');
toast.dismiss(toastId); // Close a specific notification
toast.dismiss(); // Close all notifications
4.2 Action Buttons
You can add interactive buttons to notifications:
toast('File saved', {
action: {
label: 'Undo',
onClick: () => console.log('Undo operation'),
},
});
4.3 Stacking Effect
When multiple notifications appear simultaneously, sonner automatically stacks them and displays them with animation. You can control the number of visible notifications using the visibleToasts property, or set expand={false} to limit stacking.
4.4 Swipe to Dismiss
sonner supports swipe-to-dismiss animations by default. Users can close notifications by swiping with a mouse or touch, with no additional configuration required.
5. Advantages and Use Cases
Advantages:
- Simple to use: No need for complex contexts or state management.
- Attractive defaults: Modern default styles and animations.
- Flexibility: Supports everything from simple messages to complex custom components.
- Excellent performance: Lightweight with smooth animations.
Use Cases:
- Form submission feedback (success/failure).
- Network request status indicators.
- User action confirmations (e.g., “Added to cart”).
- Real-time event notifications (e.g., new message alerts).
6. Important Notes
- Server Component Compatibility: In frameworks like Next.js,
<Toaster />can be placed in server components, but thetoastfunction needs to be called on the client side (i.e., with theuse clientdirective). - Initial Rendering Issues: If you need to display a notification when a component mounts, it’s recommended to wrap the
toastcall in asetTimeoutto avoid hydration issues:useEffect(() => { setTimeout(() => toast('Welcome back!'), 0); }, []);
7. Summary
sonner is a powerful and easy-to-use React toast notification library. Its core consists of the <Toaster /> component and the toast function, providing rich functionality through a clean API, including various notification types, Promise support, custom styles, and interactivity. Whether you want to quickly add notification features or need a highly customized notification system, sonner is worth trying.
Comments