DEV Community

Cover image for Getting Started with React Toastify: Enhance Your Notifications
Arnab Chatterjee
Arnab Chatterjee

Posted on • Originally published at codeparrot.ai

Getting Started with React Toastify: Enhance Your Notifications

Introduction

In modern web applications, delivering real-time feedback to users is crucial for maintaining a smooth and engaging experience. Notifications play a pivotal role in communicating important events, such as successful actions, errors, or warnings, without disrupting the user’s workflow. This is where React Toastify comes into play. It is a popular library that simplifies the process of adding customizable toast notifications to React applications. Unlike traditional alert boxes, which can interrupt a user’s journey, toast notifications appear in a subtle and elegant manner, ensuring that important information is conveyed without taking the user out of their current context.

With Toastify, developers can easily implement notifications that look great and are highly flexible, allowing for customization of position, style, and timing—all while being easy to set up and use. This makes it an indispensable tool for developers looking to enhance the user experience through effective feedback mechanisms.

Why Use React Toastify?

Toast notifications are essential in many common scenarios in web applications. For instance, after a user submits a form, you may want to display a success message to confirm the action was completed, or an error message if something went wrong. Similarly, when dealing with API calls, toast notifications can inform the user of the outcome, such as a successful data retrieval or an error.

React-Toastify makes handling these notifications seamless and efficient. Here are some key benefits that set it apart from default browser alerts and other libraries:

  • Easy to Integrate: It is simple to set up, requiring minimal configuration to start displaying notifications. Its intuitive API makes it accessible even for beginners, allowing developers to add toast notifications quickly without complex setup.
  • Customizable Design and Positioning: One of Toastify's standout features is its ability to customize the appearance and behavior of notifications. You can easily modify the style, position them anywhere on the screen (e.g., top-right, bottom-left), and even create custom transitions. This flexibility helps to maintain a consistent UI/UX across your application.
  • Supports Both Automatic and Manual Dismissal: Toastify gives you control over how long notifications stay visible. You can opt for automatic dismissal after a specified time or allow users to manually close the notifications, providing a better user experience based on the context.

  • Comparison with Default Browser Alerts: Default browser alerts are intrusive and block user interaction until dismissed. Toastify, on the other hand, provides non-intrusive, elegant toasts that appear in the corner of the screen and allow users to continue interacting with the page. It also supports more advanced features, such as different toast types (success, error, info) and richer styling, which are not possible with browser alerts.

By integrating React-Toastify into your React applications, you get a robust and customizable way to manage notifications, making it easier to provide feedback to users while maintaining a smooth, modern user experience.

Installation and Setup

Getting started with React-Toastify is straightforward and requires just a few steps. Here’s how you can install and set it up in your React project:

Step 1: Install React Toastify

First, you need to add the React-Toastify package to your project. Use the following command in your terminal:

npm install react-toastify
Enter fullscreen mode Exit fullscreen mode

Step 2: Import and Use React Toastify in Your Project

Once the package is installed, you need to import React Toastify and its core components into your React project. At a minimum, you should import the ToastContainer, which is responsible for rendering the toast notifications on the screen.

Here’s how to set it up:

  1. Import ToastContainer and toast into your component.
  2. Ensure the ToastContainer is included in your component’s JSX.
  3. Trigger a toast notification using the toast function.

Example:

import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

const App = () => {
  const notify = () => toast("This is a toast notification!");

  return (
    <div>
      <h1>React Toastify Example</h1>
      <button onClick={notify}>Show Notification</button>
      <ToastContainer />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 3: Add Toast Styles

Don’t forget to import the React Toastify CSS file to apply the default styling for your notifications:

import 'react-toastify/dist/ReactToastify.css';
Enter fullscreen mode Exit fullscreen mode

Now, when you click the button, a toast notification will appear on the screen. The ToastContainer can be positioned anywhere in your app, and the toasts will automatically appear within it. You can further customize the appearance and behavior of the toast, which we will explore in the following sections.

Basic Usage of React Toastify

Once you have React Toastify set up, you can easily trigger various types of notifications based on user actions. Let's explore how to use it to display different toast notifications for success, error, info, and warning messages.

Example 1: Triggering a Success Notification

A common use case for a success notification is after a form submission. You can trigger it using the following code:

toast.success("Form submitted successfully!");
Enter fullscreen mode Exit fullscreen mode

This will display a success message styled with a green icon, indicating a positive action.

Example 2: Error Notification

You can also display an error message when something goes wrong, such as a failed API call or form validation error:

toast.error("Something went wrong. Please try again!");
Enter fullscreen mode Exit fullscreen mode

This shows a red-colored toast indicating an issue that requires the user's attention.

Example 3: Info Notification

Info notifications are useful when you want to inform the user about a status or update without implying success or failure. For example:

toast.info("New updates are available!");
Enter fullscreen mode Exit fullscreen mode

Example 4: Warning Notification

If you need to alert the user to potential issues or important warnings, you can use the warning notification:

toast.warn("Your session is about to expire!");
Enter fullscreen mode Exit fullscreen mode

This shows an orange toast, typically used for warnings or cautions.

import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

const App = () => {
  const showToasts = () => {
    toast.success("Form submitted successfully!");
    toast.error("Something went wrong. Please try again!");
    toast.info("New updates are available!");
    toast.warn("Your session is about to expire!");
  };

  return (
    <div>
      <h1>React Toastify Notifications</h1>
      <button onClick={showToasts}>Show All Notifications</button>
      <ToastContainer />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

With this code, clicking the button will trigger all types of notifications, allowing you to see how each one looks and behaves in your application.

Customizing Toast Notifications

One of the great features of React Toastify is its flexibility in customizing toast notifications to fit the look and feel of your application. You can easily adjust the position, duration, and even styling to suit your needs. Let’s walk through some of these customizations.

Customizing Position

React Toastify allows you to position toast notifications in various locations on the screen. By default, toasts are displayed in the top-right corner, but you can customize their position using the position property of the ToastContainer or while triggering individual toasts.

Available positions:

  • top-right (default)
  • top-center
  • top-left
  • bottom-right
  • bottom-center
  • bottom-left

Here’s an example of how to change the position of toasts globally via the ToastContainer:

<ToastContainer position="bottom-left" />
Enter fullscreen mode Exit fullscreen mode

If you want to customize the position of individual toasts, you can pass the position option like this:

toast.success("Operation successful!", {
  position: "top-center"
});

Enter fullscreen mode Exit fullscreen mode

This will display the success notification at the top-center of the screen.

Adjusting the Auto-Dismiss Timer

toast.info("This will disappear in 3 seconds!", {
  autoClose: 3000
});
Enter fullscreen mode Exit fullscreen mode

If you want the toast to stay on screen until the user manually dismisses it, set autoClose to false:

toast.warn("This requires manual dismissal.", {
  autoClose: false
});

Enter fullscreen mode Exit fullscreen mode

Customizing Toast Styling

React Toastify provides the flexibility to style your toasts either through CSS classes or inline styles. You can pass a custom CSS class to the className or bodyClassName options to style the overall toast or its content.
Here’s an example of using a custom CSS class to style a toast:

toast("Custom styled toast!", {
  className: "custom-toast",
  bodyClassName: "custom-toast-body",
  autoClose: 5000
});
Enter fullscreen mode Exit fullscreen mode

In your CSS file, you can define the styling:

.custom-toast {
  background-color: #333;
  color: #fff;
}

.custom-toast-body {
  font-size: 18px;
}

Enter fullscreen mode Exit fullscreen mode

This gives you complete control over how your notifications appear, allowing you to match the toast design with your application’s overall theme.

Advanced Features of React Toastify

React Toastify offers useful features to enhance the functionality of your toast notifications. Here's how you can leverage progress bars, custom icons, transitions, and event listeners.

Progress Bars in Toast Notifications

By default, React Toastify includes a progress bar that indicates how long the toast will stay visible. To disable the progress bar:

toast.info("No progress bar", { hideProgressBar: true });
Enter fullscreen mode Exit fullscreen mode

Custom Icons and Transitions

You can replace default icons with custom icons for a more personalized look:

toast("Custom Icon", { icon: "🔥" });
Enter fullscreen mode Exit fullscreen mode

To apply custom transitions like Bounce:

toast("Bounce Animation", { transition: Bounce });
Enter fullscreen mode Exit fullscreen mode

Adding Event Listeners to Toasts

React Toastify allows you to add event listeners to handle custom actions, such as on click:

toast.info("Click me!", { onClick: () => alert("Toast clicked!") });
Enter fullscreen mode Exit fullscreen mode

You can also trigger actions when a toast is closed:

toast.success("Success!", { onClose: () => console.log("Toast closed") });
Enter fullscreen mode Exit fullscreen mode

Best Practices for Using React Toastify

To ensure that toast notifications enhance rather than hinder the user experience, it's important to follow best practices. Here are some guidelines to consider:

  1. Use Notifications Sparingly

    While notifications can be helpful, overusing them can frustrate or distract users. Reserve toast notifications for important updates, such as confirming successful actions (e.g., form submissions) or displaying error messages that require attention.

  2. Choose the Right Notification Type

    Use appropriate toast types (success, error, info, warning) to convey the correct tone. For instance, success messages should be used for completed actions, while warnings should be reserved for potential issues.

  3. Avoid Blocking User Actions

    Since toasts are non-intrusive, they should not block important user interactions. Display notifications in a way that doesn’t prevent users from continuing their tasks.

  4. Customize Timing Based on Context

    Set reasonable auto-dismiss times for toasts. Error messages might need to stay longer, while success notifications can disappear quickly. For critical issues, consider letting users manually dismiss the notification.

Conclusion

React-Toastify makes implementing notifications in React applications seamless and efficient, offering a flexible solution for delivering real-time feedback to users. With its customizable design, positioning options, and support for advanced features like progress bars and event listeners, it simplifies the notification process while allowing for great control over the user experience.

By following best practices and using toast notifications wisely, you can enhance user interaction without overwhelming them. For more detailed information and advanced use cases, be sure to check out the official React Toastify documentation.

Top comments (1)

Collapse
 
kristoffer91 profile image
Kristoffer Öhrn

Very interesting. Thank you!