DEV Community

Cover image for Notification Nirvana: How to Notify with Toastify
De'Juan Ellsworth
De'Juan Ellsworth

Posted on

Notification Nirvana: How to Notify with Toastify

Introduction

User notifications are a crucial component of any web application. They provide real-time feedback to users, enhancing their experience and keeping them informed about important events and actions. In this blog, we'll explore how to create user-friendly notifications in React applications using the React Toastify library.

Getting Started with React Toastify

Before you can start using React Toastify for creating toast notifications in your project, you need to perform some initial setup. Follow these steps to import and configure React Toastify effectively. To get started:

Installation

The first step is to install React Toastify in your React project. You can do this using npm or yarn, depending on your package manager preference. Open your terminal and run one of the following commands:

npm install react-toastify
yarn add react-toastify
Enter fullscreen mode Exit fullscreen mode

Configuration

Now we're ready to configure React Toastify based on projects requirements. Here's an example of how to set up the ToastContainer component in your application:

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

function App() {
  return (
    <div>
      {/* Include the ToastContainer component */}
      <ToastContainer
        position="top-right" // Position where toast notifications will appear
        autoClose={5000}     // Time in milliseconds before auto-closing a toast
        hideProgressBar={false} // Show or hide the progress bar
        newestOnTop={true}      // Display newer toasts on top
        closeOnClick={true}     // Close a toast when clicked
        rtl={false}             // Right-to-left text direction (true/false)
        pauseOnFocusLoss={true} // Pause toast when the window loses focus (true/false)
      />

      {/* Your React components */}
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

Basic Usage

Creating toast notifications with React Toastify is straightforward and offers a variety of options for customization. The core of displaying notifications lies in the toast() function, which allows you to create and display notifications with ease.

import { toast } from 'react-toastify';

function ExampleComponent() {
  const showToast = () => {
    toast.success('This is a success notification');
  };

  return (
    <div>
      <button onClick={showToast}>Show Notification</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Types of Toasts

React Toastify supports various types of toast notifications:
Toast

  • Success: Indicate successful actions.
  • Error: Display error messages.
  • Warning: Warn users about important information.
  • Info: Provide informational messages.

You can create each type of toast using the respective functions (toast.success(), toast.error(), etc.).

Advanced Features

React Toastify offers advanced features for customization and control:

Custom Icons

custom toast

You can use custom icons in your toast notifications to make them more visually appealing and informative.

Promises

function submitForm() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const isSuccess = true;
      if (isSuccess) {
        resolve('Form submitted successfully!');
      } else {
        reject('Form submission failed.');
      }
    }, 2000); // Simulating a 2-second delay
  });
}

Enter fullscreen mode Exit fullscreen mode

promise

When the submitForm Promise resolves successfully, a success toast is displayed with the success message. An optional pending toast can be used to inform users of pending events. If the Promise rejects (i.e., the form submission fails), an error toast is displayed with the error message.

Transition Effects

Customize transition effects for your notifications to create engaging user experiences. Simply import the toast transition properties, then set the value for your selected container on the transition property.

import { Flip, Bounce, Slice, Zoom, ToastContainer } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';

function App() {
  return (
    <div>
      <ToastContainer
        transition={Flip}/>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

Follow these best practices when using React Toastify:

  • Keep notifications concise and clear.
  • Use appropriate types for different scenarios.
  • Ensure accessibility and screen reader compatibility.
  • Handle toast stacking and positioning gracefully.

Conclusion

In the realm of web development, React Toastify emerges as a pivotal tool for user notifications. It epitomizes simplicity, versatility, and effectiveness. Spanning from initial configuration to the incorporation of advanced features, React Toastify excels at delivering timely and user-friendly notifications. Whether you're a seasoned developer or just starting on your web development journey, React Toastify is a reliable companion that elevates your applications by enhancing user interactions.

References

React Toastify Official Documentation

React Toastify GitHub Repository

Top comments (0)