Various toast notifications displayed on a computer screen with React logo

React-Toastify: Creating Dynamic Notifications in React Apps

The Gray Cat
The Gray Cat

React-Toastify is a popular library that makes adding notifications to your React applications a breeze. Whether you’re building a simple app or a complex web application, React-Toastify provides an easy-to-use API for creating informative and visually appealing toast notifications. In this article, we’ll explore how to use React-Toastify effectively, from basic setup to more advanced use cases.

Installation

Let’s start by installing React-Toastify in your project. You can use either npm or yarn:

// Using npm
npm install --save react-toastify

// Using yarn
yarn add react-toastify

Basic Usage

Once installed, you can start using React-Toastify in your application. Here’s a simple example to get you started:

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

const App: React.FC = () => {
  const notify = () => toast("Wow so easy!");

  return (
    <div>
      <button onClick={notify}>Notify!</button>
      <ToastContainer />
    </div>
  );
}

export default App;

In this example, we import the necessary components and CSS from React-Toastify. The ToastContainer component is where your notifications will appear, and the toast function is used to trigger notifications.

Don’t forget to import the CSS file to ensure proper styling of your toasts.

Advanced Usage

React-Toastify offers many customization options and advanced features. Let’s explore some of them:

Handling autoClose

You can control how long a toast notification stays visible using the autoClose prop:

import React from 'react';
import { toast, ToastContainer } from 'react-toastify';

function Example() {
  const notify = () => {
    toast("Default notification");
    toast("Closes after 8 seconds", { autoClose: 8000 });
    toast("Doesn't auto-close", { autoClose: false });
  };

  return (
    <div>
      <button onClick={notify}>Notify</button>
      <ToastContainer />
    </div>
  );
}

Rendering Custom Content

React-Toastify allows you to render custom content, including React components, inside your toasts:

import React from 'react';
import { toast } from 'react-toastify';

const CustomToast: React.FC<{ closeToast: () => void }> = ({ closeToast }) => (
  <div>
    <h3>Custom Toast Content</h3>
    <p>This is a React component inside a toast!</p>
    <button onClick={closeToast}>Close</button>
  </div>
);

function Example() {
  const notify = () => toast(<CustomToast />);

  return <button onClick={notify}>Show Custom Toast</button>;
}

Removing Toasts Programmatically

You can remove toasts programmatically using their IDs:

import React from 'react';
import { toast } from 'react-toastify';

function Example() {
  const toastId = React.useRef<string | number | null>(null);

  const notify = () => {
    toastId.current = toast("This toast can be dismissed programmatically");
  };

  const dismiss = () => {
    if (toastId.current) {
      toast.dismiss(toastId.current);
    }
  };

  return (
    <div>
      <button onClick={notify}>Notify</button>
      <button onClick={dismiss}>Dismiss</button>
    </div>
  );
}

Handling Promises

React-Toastify provides a convenient way to handle promises and display different toasts based on the promise state:

import React from 'react';
import { toast } from 'react-toastify';

function Example() {
  const handlePromise = () => {
    const promiseExample = new Promise((resolve, reject) => {
      setTimeout(() => resolve("Success!"), 3000);
    });

    toast.promise(promiseExample, {
      pending: 'Loading...',
      success: 'Data loaded successfully',
      error: 'Error loading data'
    });
  };

  return <button onClick={handlePromise}>Load Data</button>;
}

Using Custom Icons

You can customize the icons displayed in your toasts:

import React from 'react';
import { toast } from 'react-toastify';
import { FaCheckCircle, FaExclamationCircle } from 'react-icons/fa';

function Example() {
  const notifySuccess = () => toast.success("Success!", {
    icon: <FaCheckCircle />
  });

  const notifyError = () => toast.error("Error!", {
    icon: <FaExclamationCircle />
  });

  return (
    <div>
      <button onClick={notifySuccess}>Success</button>
      <button onClick={notifyError}>Error</button>
    </div>
  );
}

Styling and Customization

React-Toastify provides various options for styling and customizing your toasts. You can override CSS variables, use custom CSS classes, or even create your own animations. Here’s a quick example of customizing toast styles:

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

function App() {
  return (
    <div>
      {/* Your app content */}
      <ToastContainer
        position="bottom-right"
        autoClose={5000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="colored"
      />
    </div>
  );
}

Conclusion

React-Toastify is a powerful and flexible library that makes adding notifications to your React applications simple and enjoyable. With its easy setup, extensive customization options, and advanced features like promise handling and custom content rendering, you can create informative and visually appealing notifications that enhance the user experience of your app.

Remember to explore the official documentation for more advanced features and customization options. Happy notifying!

Comments