Futuristic toaster emitting holographic notifications in a modern kitchen

Sonner: Orchestrating Toast Notifications in React

The Gray Cat
The Gray Cat

Sonner is an opinionated toast component for React that brings a fresh approach to displaying notifications in your applications. With its simple API and extensive customization options, Sonner makes it easy to create, manage, and style toast notifications that seamlessly integrate with your React projects. Whether you need to display success messages, error alerts, or custom content, Sonner has you covered with its versatile and user-friendly features.

Serving Up Toasts: Key Features

Sonner comes packed with a variety of features that make it stand out in the world of React toast libraries:

  • Flexible Positioning: Place toasts anywhere on the screen with ease.
  • Rich Customization: Tailor the appearance and behavior of toasts to match your app’s design.
  • Promise Integration: Automatically update toasts based on promise states.
  • Custom Components: Create fully custom toast content using JSX.
  • Accessibility: Built with accessibility in mind, including keyboard navigation.
  • TypeScript Support: Fully typed for a smooth development experience.

Preparing the Kitchen: Installation

To start using Sonner in your React project, you’ll need to install it first. You can do this using npm or yarn:

npm install sonner
# or
yarn add sonner

The First Slice: Basic Usage

Once installed, you can start using Sonner in your React application. Here’s how to set it up and create your first toast:

Setting the Table

First, add the <Toaster /> component to your app. This component acts as the container for all your toasts:

import { Toaster } from 'sonner';

function App() {
  return (
    <div>
      {/* Your app content */}
      <Toaster />
    </div>
  );
}

Toasting Your First Notification

Now that the <Toaster /> is in place, you can use the toast() function to create notifications from anywhere in your app:

import { toast } from 'sonner';

function MyComponent() {
  return (
    <button onClick={() => toast('Hello, Sonner!')}>
      Show Toast
    </button>
  );
}

This code will display a simple toast with the message “Hello, Sonner!” when the button is clicked.

Gourmet Toasts: Advanced Usage

Sonner offers a variety of advanced features that allow you to create more complex and interactive toasts.

Flavored Toasts: Success and Error Notifications

Sonner provides pre-styled toasts for common scenarios:

toast.success('Operation completed successfully!');
toast.error('An error occurred. Please try again.');

These methods automatically add appropriate icons and styles to your toasts.

Interactive Toasts: Adding Actions

You can make your toasts interactive by adding action buttons:

toast('File uploaded', {
  action: {
    label: 'Undo',
    onClick: () => console.log('Undo clicked'),
  },
});

This creates a toast with an “Undo” button that triggers a callback when clicked.

Asynchronous Toasts: Promise Integration

Sonner can automatically update toasts based on the state of a promise:

const uploadFile = () => new Promise(resolve => setTimeout(resolve, 2000));

toast.promise(uploadFile(), {
  loading: 'Uploading file...',
  success: 'File uploaded successfully!',
  error: 'Failed to upload file.',
});

This code will show a loading toast while the promise is pending, and then update it to show success or error based on the promise result.

Customizing the Recipe: Styling and Theming

Sonner allows for extensive customization to match your app’s design:

Global Styling

You can set global styles for all toasts using the <Toaster /> component:

<Toaster
  toastOptions={{
    style: { background: '#333', color: '#fff' },
    className: 'my-toast-class',
  }}
/>

Individual Toast Styling

For more granular control, you can style individual toasts:

toast('Custom styled toast', {
  style: { border: '2px solid #00f' },
  className: 'special-toast',
});

Theme Customization

Sonner supports light and dark themes, as well as a system theme that adapts to the user’s preferences:

<Toaster theme="dark" />

The Perfect Toast: Best Practices

To get the most out of Sonner, consider these best practices:

  1. Keep it Brief: Toast messages should be concise and to the point.
  2. Use Appropriate Types: Utilize success, error, and other types for clear communication.
  3. Limit Actions: If a toast requires multiple actions, consider using a modal instead.
  4. Mind the Position: Choose a toast position that doesn’t interfere with important UI elements.
  5. Accessibility: Ensure your toasts are accessible by using clear language and providing enough contrast.

Wrapping Up: Conclusion

Sonner offers a delightful way to add toast notifications to your React applications. Its intuitive API, extensive customization options, and thoughtful features make it a standout choice for developers looking to enhance their user interfaces with informative and interactive notifications. By leveraging Sonner’s capabilities, you can create a more engaging and responsive experience for your users, keeping them informed and in control as they navigate your application.

Whether you’re building a simple website or a complex web application, Sonner provides the tools you need to toast your successes, warn of potential issues, and guide users through various processes with style and efficiency. So go ahead, give Sonner a try, and elevate your React project’s notification game to the next level!

For more insights on enhancing your React applications, you might want to explore articles on React animations with Framer Motion or creating responsive layouts with React Schematic. These complementary libraries can work alongside Sonner to create even more dynamic and engaging user interfaces.

Comments