React Toastify: Easy and Customizable Toast Notifications

React-Toastify-Feature.jpg

React Toastify makes it effortless to give users instant feedback in your React applications. From simple success messages to interactive notifications, this tutorial covers everything you need to start using toast notifications effectively.

Table of Contents:

What are Toast Notifications?

Imagine this: you complete a form on a website to register for something or save some information. Then, nothing happens. You are standing there waiting, and you have no idea if the form worked successfully or not. Not great for user experience, right?

This is where toast notifications come into play.

A toast notification is a short-term message that appears in your application to tell the user what is going on. Unlike the older alert() boxes that freeze everything until you click on the OK button, toasts are non-blocking; they appear, convey the message, and leave.

Why use React Toastify?

All React applications require some sort of feedback. When a user clicks a button, submits a form, or fires an action in an app, they need feedback as to what happened. No feedback creates a sense of an unresponsive app. Errors are never caught. Success is never clarified. 

React Toastify provides non-blocking notifications for small messages that appear for just a few moments without interaction from the user. These toasts confirm and denote feedback for the user to know immediately: success, error, warning, or inform them. Every interaction is now intuitively transparent. 

In addition to basic notification suits, React Toastify covers the following:

  • Positioning and stacking: A stack of messages will be delivered in sequence, and if stacking does occur, they won’t block anything else in the UI.. 
  • Timing and auto-dismissal: The toasts will auto-dismiss based on how long the developer chooses, creating a cleaner interface to work with. 
  • Customization: Colors, icons, and even custom React components can be added for each toast. 
  • Animation: React Toastify smooths out exiting and entering messages in a pleasing manner of interruptions when notifications or messages come in or out. 
  • Promise Tracking: React Toastify also allows and tracks any async operation in the same manner and displays when something is loaded, succeeded, or errored out right back to the user in a toaster. 

React Toastify provides simple messages, reliable feedback to the user, and is even user-friendly to the developer. Lightweight, maintained, and simple to add to any React project.

Installation & Setup of React Toastify

Getting React Toastify up and running in your React project is a straightforward process, whether you created the project using Vite, Create React App, or Next.js.

Step 1: Install the React Toastify Package

You can install the React Toastify package using either npm or Yarn.

npm install react-toastify

or

yarn add react-toastify

You will get a confirmation message in the terminal that looks like this:

installation

Step 2: Import Styles and Components

React Toastify comes with a ready-made CSS file and key components. Import them in your root component (usually App.js or App.jsx):

import 'react-toastify/dist/ReactToastify.css';
import { ToastContainer, toast } from 'react-toastify';
  • ToastContainer is where the notifications are rendered.
  • toast is the function used to trigger notifications.

Step 3: Add ToastContainer

Place <ToastContainer /> in your component tree, ideally near the top level so notifications are visible throughout the app:

function App() {
  return (
    <div className="App">
      <h1>React Toastify Demo</h1>
      <ToastContainer />
    </div>
  );
}

At this point, React Toastify is fully installed and ready to use. Any toast notifications triggered with toast() will automatically appear within the <ToastContainer />.

This sets up the foundation. The next section, Basic Usage, will show how to trigger notifications, the different types, and simple examples.

Basic Usage of React Toastify

Now that you have configured your environment and installed all the dependencies, let us explore a basic use case of React Toastify. Once you have installed React Toastify and the <ToastContainer /> is in place, you can trigger toasts with ease. The toast() function is your workhorse; simply call it anywhere in your code, and a notification will appear.

1. Simple Notification using React Toastify

The simplest toast is just a string:

toast(‘Hello! This is a basic notification.’);

Let’s go ahead and attach it to a button so that the message is triggered every time we click it. Here is what your App.js file would look like:

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

function App() {
  return (
    <div className="App">
      <h1>React Toastify Demo</h1>
      <button onClick={() => toast('Button clicked!')}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}

export default App;

When executed, a small notification will pop up in the default position (top-right) and disappear after 5 seconds.

simple notif

2. Different Types of Notifications

React Toastify comes with predefined types to make messages instantly recognizable:

toast.success('Success!');   // Green
toast.error('Error! ');       // Red
toast.info('Info message ');  // Blue
toast.warn('Warning! ');      // Yellow

Each type comes with default styling, making it easier for users to identify the message without reading the text carefully.

Get 100% Hike!

Master Most in Demand Skills Now!

React Toastify Customization

The advantage of React Toastify lies in how simple it makes customizing notifications to fit your application’s personality. You’re in full control of the defaults, position, duration, motion, styling, and even what content is inside the toast.

1. Positioning the Toast

By default, toasts appear at the top-right corner. But you can move them to any of six positions with just one prop:

<ToastContainer position="bottom-left" />
  • top-left
  • top-center
  • top-right (default)
  • bottom-left
  • bottom-center
  • Bottom-right

Here is the App.js code, where you can see how all the positions look in your project:

// Filename: App.js
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default function App() {
  const notify = () => {
    toast.success("Closes in 3s", { autoClose: 3000 });
    toast.info("Closes in 7s", { autoClose: 7000 });
    toast.warning("Stays until closed manually", { autoClose: false });
  };

  return (
    <div style={{ textAlign: "center", marginTop: "2rem" }}>
      <h2>Auto-Close Demo</h2>
      <button onClick={notify}>Show Toasts</button>
      <ToastContainer />
    </div>
  );
}

Output:

positioning the toast

So, if your design already has a header or floating button at the top, you can move your toast out of the way with a single change.

2. Changing the Auto-Close Duration

Not every message deserves equal time on screen. You might want success messages to disappear fast, and warnings to linger a little longer.

// Filename: App.js
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default function App() {
  const notify = () => {
    toast.success("Closes in 3s", { autoClose: 3000 });
    toast.info("Closes in 7s", { autoClose: 7000 });
    toast.warning("Stays until closed manually", { autoClose: false });
  };

  return (
    <div style={{ textAlign: "center", marginTop: "2rem" }}>
      <h2>Auto-Close Demo</h2>
      <button onClick={notify}>Show Toasts</button>
      <ToastContainer />
    </div>
  );
}

Output:

auto close duration

You’ll see the toasts vanish at different times, one quickly, one slower, and one that waits for your click. 

3. Styling Toasts with Custom CSS

You can match your app’s color theme using the className prop.

// Filename: App.js
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import "./styles.css"; // Create this file

export default function App() {
  const notify = () => {
    toast("Custom Styled Toast", { className: "custom-toast" });
  };

  return (
    <div style={{ textAlign: "center", marginTop: "2rem" }}>
      <h2>Styled Toast Demo</h2>
      <button onClick={notify}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}

Don’t forget to create a styles.css file in your projects and add:

.custom-toast {
  background-color: #1e293b;
  color: #fff;
  font-weight: 600;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

Output:

custom css

4. Displaying Custom Components Inside Toasts

Toasts can do more than display text; they can hold interactive JSX elements.

// Filename: App.js
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default function App() {
  const showInteractiveToast = () => {
    toast(
      <div>
        <strong>File uploaded!</strong>
        <button
          style={{
            marginLeft: "10px",
            backgroundColor: "#2563eb",
            color: "#fff",
            border: "none",
            borderRadius: "5px",
            padding: "5px 10px",
            cursor: "pointer",
          }}
          onClick={() => alert("Opening file...")}
        >
          Open
        </button>
      </div>
    );
  };

  return (
    <div style={{ textAlign: "center", marginTop: "2rem" }}>
      <h2>Custom Component Toast</h2>
      <button onClick={showInteractiveToast}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}

Output:

custom component

A toast appears with a small “Open” button. Clicking it triggers another alert, showing how you can mix feedback with functionality.

5. Handling Events (onClick and onClose)

You can run specific logic when a toast is clicked or closed.

// Filename: App.js
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default function App() {
  const handleToast = () => {
    toast("Click or close this toast!", {
      onClick: () => console.log("Toast clicked"),
      onClose: () => console.log("Toast closed"),
    });
  };

  return (
    <div style={{ textAlign: "center", marginTop: "2rem" }}>
      <h2>Event Hooks Demo</h2>
      <button onClick={handleToast}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}

Output:

event hooks

Try clicking the toast; you’ll see messages logged in the console each time you interact with it, like so.

handling events

As you can see, React Toastify isn’t just about displaying messages. It’s a design tool that lets your notifications speak your app’s visual language, with control, animation, and tone that match your product’s vibe.

Real-World React Toasify Examples

The most valuable toast notifications tackle problems users have. It is not enough to display a message. You must understand user behavior, timing, and context. The following are some usual situations: 

1. API Calls: Success, Error, and Loading States

Problem: When fetching data from an API, users often don’t know what’s happening. Without feedback, they might click multiple times, leave the page, or assume something broke.

Solution: Use toast.promise to handle pending, success, and error states in a single, clean workflow.

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

function ApiToastDemo() {
 // useState to manage loading state and disable button while fetching data
  const [loading, setLoading] = useState(false);

  const fetchData = () => {
    setLoading(true); // indicate that API call has started

    // simulate an API call with a Promise

    const apiCall = new Promise((resolve, reject) => {
      setTimeout(() => {
        // Randomly succeed or fail to simulate real-world unpredictability

        Math.random() > 0.5 ? resolve('Data loaded successfully!') : reject('API call failed!');
      }, 2000);
    });

    // toast.promise provides automatic notifications for pending, success, and error states

    toast.promise(apiCall, {
      pending: 'Fetching data...', // shows while API call is in progress
      success: 'Data loaded successfully!', // shows if API call succeeds
      error: 'Failed to fetch data ', // shows if API call fails
    }).finally(() => setLoading(false)); // reset loading state regardless of success/failure
  };

  return (
    <div style={{ padding: '2rem' }}>
      <button onClick={fetchData} disabled={loading}>
        {loading ? 'Loading...' : 'Fetch Data'}
      </button>
      <ToastContainer />
    </div>
  );
}
export default ApiToastDemo;

Output:

API calls
  • Shows a “Fetching data…” toast while waiting.
  • Automatically updates to success or error depending on the result.
  • Prevents the user from clicking multiple times unnecessarily.

2. Form Submission Feedback

Problem: Users submit a form, but the response isn’t clear. They don’t know if their action succeeded, failed, or is still processing.

Solution: Toast notifications can instantly inform the user.

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

function FormToastDemo() {
  const handleSubmit = (e) => {
    e.preventDefault(); // prevent default form submission
    const success = Math.random() > 0.5; // randomly decide if submission succeeded
  
  // show appropriate toast based on submission result
    if (success) {
      toast.success('Form submitted successfully!', { autoClose: 3000 });
    } else {
      toast.error('Form submission failed. Try again!', { autoClose: 3000 });
    }
  };

  return (
    <div style={{ padding: '2rem' }}>
      <form onSubmit={handleSubmit}>
        <input placeholder="Enter something" />
        <button type="submit">Submit</button>
      </form>
      <ToastContainer position="top-right" />
    </div>
  );
}

export default FormToastDemo;

Output:

form submission
  • Success or error toast appears immediately after submission.
  • Users know exactly what happened, improving trust and UX.

3. Long Processes: Show Progress

Problem: Some operations take longer, like file uploads or data processing. Users may think the app is frozen if there’s no feedback.

Solution: Use persistent toast notifications with autoClose={false} and update them programmatically.

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

function UploadToastDemo() {
  const uploadFile = () => {
    // Create a persistent toast that stays until manually updated

    const id = toast.info('Uploading file...', { autoClose: false });
    // Simulate file upload with setTimeout

    setTimeout(() => toast.update(id, { render: 'Upload complete!', type: toast.TYPE.SUCCESS, autoClose: 3000 }), 3000);
  };

  return (
    <div style={{ padding: '2rem' }}>
      <button onClick={uploadFile}>Upload File</button>
      <ToastContainer position="top-center" />
    </div>
  );
}

export default UploadToastDemo;

Output:

long process
  • Shows a “Uploading file…” toast that stays visible until the process completes.
  • Automatically updates to a success message when done.

4. Conditional User Actions

Problem: Sometimes you want the user to take action from the toast, like retrying a failed API call or confirming deletion.

Solution: Add buttons or clickable actions directly inside the toast.

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

function ActionToastDemo() {
  const showActionToast = () => {
    // Custom toast with a button inside for user action

    toast(
      <div>
        Something went wrong! <button onClick={() => toast.dismiss()}>Retry</button>
      </div>,
      { 
        autoClose: false,   // stays visible until dismissed
        position: 'bottom-left' // positioned at bottom-left corner
      }
    );
  };

  return (
    <div style={{ padding: '2rem' }}>
      <button onClick={showActionToast}>Show Action Toast</button>
      <ToastContainer />
    </div>
  );
}

export default ActionToastDemo;

Output:

conditional user action
  • Users see an interactive toast with a retry button.
  • Encourages immediate action without navigating away.

Key Takeaways from Real-World Scenarios

  • Interactive notifications: Allow actions directly in toasts.
  • Async feedback: Use toast.promise for API calls.
  • Form submission: Quickly show success/error toasts.
  • Long-running tasks: Persistent toasts prevent confusion.

Conclusion

Notifications may seem like a small detail, but they often decide how “polished” your app feels. React Toastify takes something as ordinary as alerts and turns them into a smooth, modern experience that users actually enjoy. It’s simple to use, easy to customize, and fits naturally into any React workflow.

At its core, React Toastify is more than just a tool for showing messages — it’s a way to build trust with users. Every toast that appears and disappears at the right moment makes your app feel more alive and intentional. That’s what separates a functional project from a professional one.

If you want to go beyond toasts and master how all the pieces of a modern web app connect, from React frontends to robust APIs and databases, check out our Full Stack Development Course. It’s built to help you think like a developer, not just write code that works.

React Toastify: Easy and Customizable Toast Notifications – FAQs

Q1. What is React Toastify used for?

React Toastify is a lightweight React library that helps you show beautiful, non-blocking notifications, also known as “toasts.” These pop up briefly to inform users about actions like form submissions, API responses, or success/error messages.

Q2. Is React Toastify better than using alert() in JavaScript?

Absolutely. The old alert() function stops everything until the user closes it. React Toastify, on the other hand, shows notifications smoothly without interrupting the flow of your app, making it far better for modern user experiences.

Q3. Can I customize the style of a toast in React Toastify?

Yes! You can fully customize your toasts, change colors, add icons, animations, or even render your own React components inside them. This helps the notifications blend perfectly with your app’s theme and design.

Q4. How do I show different types of messages using React Toastify?

React Toastify provides built-in functions for different message types, like toast.success(), toast.error(), toast.info(), and toast.warn(). Each one comes with its own visual style to make your messages instantly recognizable.

Q5. Can React Toastify be used in Next.js or Vite projects?

Yes, it works seamlessly with all major React frameworks, including Create React App, Vite, and Next.js. Just install the package, import the CSS, and include in your root component, you’re good to go!

About the Author

Software Developer | Technical Research Analyst Lead | Full Stack & Cloud Systems

Ayaan Alam is a skilled Software Developer and Technical Research Analyst Lead with 2 years of professional experience in Java, Python, and C++. With expertise in full-stack development, system design, and cloud computing, he consistently delivers high-quality, scalable solutions. Known for producing accurate and insightful technical content, Ayaan contributes valuable knowledge to the developer community.

Full Stack Developer Course Banner