Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use React Toastify and Create Effective Notifications

Notifications are user interface elements that communicate information, alerts, or updates to users. They play a crucial role in enhancing user experience by providing timely feedback and keeping users informed concerning relevant events.

notification

These subtle heralds of information called Notification, wield the power to transform mundane digital interactions into engaging and dynamic experiences. Within the realm of web development, notifications stand as indispensable messengers, delivering alerts, updates and confirmations with finesse. Let us see a few reasons why notifications are important.

Why are Notifications Important?

  • FEEDBACK MECHANISM: Notifications serve as a feedback mechanism, confirming successful actions or informing users about errors or issues.

  • USER ENGAGEMENT: They help to maintain user engagement by promptly notifying users about relevant activities, events or messages.

  • TIME-SENSITIVE INFORMATION: For applications with time sensitive information e.g., messaging apps or real-time updates, notifications offer a quick way to grab user attention.

Types of Notifications

For a bit, let us take a look at common types of notifications.

  1. Toast Notifications: Commonly used for non-intrusive alerts, These are brief, unobtrusive messages that appear and disappear.

  2. Banner Notifications: These are typically found at the top or bottom of the screen, banner notifications convey vital information without disrupting the user’s flow.

  3. Modal Notifications: These type of notification pop up in the center of the screen, requiring user interaction before proceeding.

Notifications are essential elements in web development, they serve as a means to engage, inform, and provide feedback to users. The effective implementation of notifications contributes greatly to ensuring positive user experience.

Toast Notifications

toast notification

Commonly used in in mobile and desktop applications, Toast notifications provides users with non intrusive updates. They are a form of user interface feedback that appear briefly on a screen to inform users about specific events or updates in an application. They name comes from the concept of a toaster popping up toast, as they similarly “pop up” for a duration to convey information.

Toast often include a concise message, icon, and sometimes a brief CTA(call-to-action). They serve to alert users about important events such as system status changes, new messages, or completed tasks.

A key characteristic of toast notifications is their transient nature as they appear for a short duration before automatically fading away. This aims at providing information without interrupting the user’s current activity, ensuring a smooth and uninterrupted user experience. Toasts are customizable in terms of duration, appearance and behavior based on your application or project’s requirements.

They are a very important component of user experience design as they enhance the overall usability of applications by delivering timely instructions without being intrusive.

What is React-Toastify ?

react toastify

The React toastify library is a popular, lightweight and user friendly library for handling toast notifications in React applications. It simplifies the process of creating and managing toast messages, providing you with an easy-to-use solution for displaying notifications in a React environment.

Why React Toastify?

Let us look into some key features of React Toastify.

  • Ease of Use: React toastify is known for simplicity, making it accessible for developers at all levels. Minimal configuration is involved in integrating this library into your React project, allowing you to focus on the content and appearance of your toast notifications.

  • Transitions: This library supports smooth and customizable transitions for toast notifications. With this library, you can easily define entrance and exit animations, enhancing the visual appeal of notifications as they appear and disappear.

  • Dynamic content: The toast notifications can contain dynamic content, such as buttons or links, enabling you to implement interactive elements within the notifications themselves. They can be very useful in incorporating actions directly within the notification.

  • Lifecycle Events: React Toastify provides lifecycle events for different stages of a toast’s existence, allowing the execution of custom actions before, during or after the display of a notification. This can be very much useful for integrating additional functionality or handling specific events.

Other features of React toastify include RTL support, theming(light and dark mode), easy positioning.

When do you use react Toastify in react app?

Here are some scenarios where you might consider using react toastify in your react project.

  1. User Feedback: When there is the need to provide users with instant feedback on their actions, such as completing a task, submitting a form or updating settings, react toastify comes in handy.

  2. Asynchronous Operations: When dealing with asynchronous operations like API calls, you can use react toast notifications to inform users of the status of these operations. Display success messages upon successful completion and error messages if issues arise.

  3. Error Handling: You can utilize react toast notifications to communicate alerts or errors to users. Be it an successful form submission, a network error, or any unexpected issues, displaying a toast message can easily inform users about the problem without disrupting their workflow.

Remember that the decision to use React Toastify largely depends on the specific needs and design principles of your application. If your application requires a customizable and non-intrusive way to provide feedback or communicate with users, integrating React Toastify can be a practical and user-friendly solution.

How to install react-toastify?

Setting up our React Project

Use the command below to create a new react application.


npx create-react-app react-toastify

Run the next command to navigate to the newly created app directory.

	
cd react-toastify

Finally, run the command below to start the server.

npm start
//or
yarn start

Server should run in the browser as shown below

live server

Installing React Toastify

You can install React Toastify by running the command below in your project.

npm install react-toastify
// or
yarn add react-toastify

Setting up a Basic Toast Notification

Import react toastify and react-toastify CSS in your `App.js` file. Create a notification in your app function

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast("Who clicked the button?!");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer />
      </div>
    )
}
export default App;

In the image below, we see a toast message appearing each time the user clicks the button.

toast message

How do you make a Toast Message in React Toastify?

As seen in our previous example, simply create a function that can be called `onClick` of a button.

const handleNotify = () => toast("Who clicked the button?!");

Types of Toast Notifications

We have 5 types of toast notifications available in react toastify.

  1. Default

  2. info

  3. success

  4. warning

  5. error

Let us implement each type of toast notification in our code.

Default

const handleNotify = () => toast("Who clicked the button?!");

Let us apply this to our app component

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast("Who clicked the button?!");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer />
      </div>
    )
}
export default App;
default toast message

Info

const handleNotify = () => toast.info("Who clicked the button?!");

Take note of our new addition `.info`

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast.info("Who clicked the button?!");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer />
      </div>
    )
}
export default App;
info toast message

Success

Here we will attach `.success` to toast(). This notification is used to covey a success message.

const handleNotify = () => toast.success("Button successfully clicked!")
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast.success("Button successfully clicked!");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer />
      </div>
    )
}
export default App;
success toast message

Warning

In this type of notification, `.warning` is added to toast().

const handleNotify = () => toast.warning("Button has being clicked!");
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast.warning("Button has being clicked!");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer />
      </div>
    )
}
export default App;

warning toast message

Error

This type of notification is used to convey an error message. Here, `.error` is added to toast().

const handleNotify = () => toast.error("You clicked the button!");
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast.error("You clicked the button!");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer />
      </div>
    )
}
export default App;
error toast message

Notice that color changes occurred across the different notification types.

How to Position Toast Notifications

You can place your toast notifications in the following positions.

  • top-left

  • top-right

  • top-center

  • bottom-left

  • bottom-right

  • bottom-center

Let us take an example using `top-left`.

To do this, we will simply edit the `ToastContainer` and set the position property this way:

<ToastContainer
position="top-left" />
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast.error("You clicked the button!");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer position="top-left"/>
      </div>
    )
}
export default App;

in the image below, we can see that the toast notification has been positioned on the top-left corner of the screen

top-left positioning

you can also change positions using the following settings

<ToastContainer
position="top-left"
/>
<ToastContainer
position="top-right"
/>
    
<ToastContainer
position="top-center"
/>
    
<ToastContainer
position="bottom=left"
/>
<ToastContainer
position="bottom-right"
/>
    
<ToastContainer
position="bottom-center"
/>

Using HTML and CSS for Notification Custom Styling

Here is how you can customize toast notification using HTML and CSS.

A number of CSS variables are exposed by the react toastify library. You can override and customize them to your taste.

Below are some variables that can be overridden

:root {
  --toastify-color-light: #fff;
  --toastify-color-dark: #121212;
  --toastify-color-info: #3498db;
  --toastify-color-success: #07bc0c;
  --toastify-color-warning: #f1c40f;
  --toastify-color-error: #e74c3c;
  --toastify-color-transparent: rgba(255, 255, 255, 0.7);
  --toastify-icon-color-info: var(--toastify-color-info);
  --toastify-icon-color-success: var(--toastify-color-success);
  --toastify-icon-color-warning: var(--toastify-color-warning);
  --toastify-icon-color-error: var(--toastify-color-error);
  --toastify-toast-width: 320px;
  --toastify-toast-background: #fff;
  --toastify-toast-min-height: 64px;
  --toastify-toast-max-height: 800px;
  --toastify-font-family: sans-serif;
  --toastify-z-index: 9999;
  --toastify-text-color-light: #757575;
  --toastify-text-color-dark: #fff;
  //Used only for colored theme
  --toastify-text-color-info: #fff;
  --toastify-text-color-success: #fff;
  --toastify-text-color-warning: #fff;
  --toastify-text-color-error: #fff;
  --toastify-spinner-color: #616161;
  --toastify-spinner-color-empty-area: #e0e0e0;
  // Used when no type is provided
  // toast("**hello**")
  --toastify-color-progress-light: linear-gradient(
    to right,
    #4cd964,
    #5ac8fa,
    #007aff,
    #34aadc,
    #5856d6,
    #ff2d55
  );
  // Used when no type is provided
  --toastify-color-progress-dark: #bb86fc;
  --toastify-color-progress-info: var(--toastify-color-info);
  --toastify-color-progress-success: var(--toastify-color-success);
  --toastify-color-progress-warning: var(--toastify-color-warning);
  --toastify-color-progress-error: var(--toastify-color-error);
}

If you are not satisfied with changing variables, you can easily override existing class.

/** This is used to define container behavior: width, position: fixed etc... **/
.Toastify__toast-container {
}
/** These are used to define the position of the ToastContainer **/
.Toastify__toast-container--top-left {
}
.Toastify__toast-container--top-center {
}
.Toastify__toast-container--top-right {
}
.Toastify__toast-container--bottom-left {
}
.Toastify__toast-container--bottom-center {
}
.Toastify__toast-container--bottom-right {
}
/** Available classes for the displayed toast **/
.Toastify__toast {
}
.Toastify__toast--rtl {
}
.Toastify__toast-body {
}
/** Use this to position the icon **/
.Toastify__toast-icon {
}
/** use this to handle the notification color and the text color based on the theme **/
.Toastify__toast-theme--dark {
}
.Toastify__toast-theme--light {
}
.Toastify__toast-theme--colored.Toastify__toast--default {
}
.Toastify__toast-theme--colored.Toastify__toast--info {
}
.Toastify__toast-theme--colored.Toastify__toast--success {
}
.Toastify__toast-theme--colored.Toastify__toast--warning {
}
.Toastify__toast-theme--colored.Toastify__toast--error {
}
.Toastify__progress-bar {
}
.Toastify__progress-bar--rtl {
}
.Toastify__progress-bar-theme--light {
}
.Toastify__progress-bar-theme--dark {
}
.Toastify__progress-bar--info {
}
.Toastify__progress-bar--success {
}
.Toastify__progress-bar--warning {
}
.Toastify__progress-bar--error {
}
/** here, colored notifications share the same progress bar color **/
.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,
.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,
.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,
.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error {
}
/** Classes for the close button. Advisable to use your own closeButton **/
.Toastify__close-button {
}
.Toastify__close-button--default {
}
.Toastify__close-button > svg {
}
.Toastify__close-button:hover,
.Toastify__close-button:focus {
}

Toast Transitions and Animations

In React Toastify, there are four provided transitions.

  1. Zoom

  2. Flip

  3. Bounce

  4. Slide

Let us cite an example using the `zoom` transition.

First, we want to import our transition properties.

import { Bounce, Slide, Zoom, ToastContainer, toast } from 'react-toastify';  

Next, we want to place our zoom transition into the toast function

const handleNotify = () => toast("This is a zoom transition !",{
    transition: Zoom
  });

Complete code snippet:

import { Bounce, Slide, Zoom, ToastContainer, toast } from 'react-toastify';    
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotify = () => toast("This is a zoom transition !",{
    transition: Zoom
  });
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        <ToastContainer />
      </div>
    )
}
export default App;

Passing CSS classes to components

There are predefined styling props that the ToastContainer will accept. You can customize the toast notification with this. They are as follows:

  • className

  • toastClassName

  • bodyClassName

  • progressClassName

  • style

toast("Creating custom", {
  className: "blue-background",
  bodyClassName: "grow-font-size",
  progressClassName: "progress-bar",
});

How to Handle Auto Close in React Toastify

The `autoClose` property is programmed to either accept duration in milliseconds or accept `false`.

import { ToastContainer, toast } from 'react-toastify';
//Close the toast after 4 seconds
    <ToastContainer
    autoClose={4000}
    />

You can also specifically close each toast at varying time intervals.

import { Bounce, Slide, Zoom, ToastContainer, toast } from 'react-toastify';    
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
function App() {
  const handleNotifyOne = () => toast("4 seconds duration", { autoClose: 4000});
  const handleNotifyTwo = () => toast("6 seconds duration", { autoClose: 6000});
	return (
	<div className='App'>
        <button onClick={handleNotifyOne}>Catch the click!</button>
        <button onClick={handleNotifyTwo}>Catch the click!</button>
        <ToastContainer/>
      </div>
    )
}
export default App;

Result:

time based notification

The toast notification can also be prevented from closing by default, the `false` statement is used instead of milliseconds.

const handleNotify = () => toast("Hello!", { autoClose: false});

How to Limit the Number of Toast Displayed

The `limit` prop allows us to control the number of toast notifications being displayed. In this example, we will display a maximum of 2 notification messages at the same.

<ToastContainer limit={2}>
import {  ToastContainer, toast } from 'react-toastify';    
import 'react-toastify/dist/ReactToastify.css';
import './App.css';

function App() {
  const handleNotify = () => toast("button clicked");
	return (
	<div className='App'>
        <button onClick={handleNotify}>Catch the click!</button>
        {/* Show a maximum of 2 notifications at the same time */}
        <ToastContainer limit={2}/>
      </div>
    )

}
export default App;

Here’s a video tutorial to help you learn more on the concept of React toastify.

What is the difference between React Toastify and Notistack?

Both `react-toastify` and `notistack` are popular libraries for adding toast notifications to your React application. They however have some differences in terms of usage and features.

Notistack

  1. Integration with Material-UI(MUI): Notistack is part of the MUI ecosystem, make it a smooth choice if you are already using MUI components in your project.

  2. Support for Stacking: It handles stacking and queuing of notifications by default.

  3. Snackbar Component: Notistack is built on MUI’s Snackbar component, this provides consistency if your application follows Material Design principles.

Want to know more about Notistack?, the video below should help

React toastify

  1. Ease of Use: The React toastify library is straightforward to use, you also have full control over the entire lifecycle of a toast.

  2. Customization: React toastify offers a customizable notification system, allowing you to style and configure toast notifications according to your taste

  3. Animation: It provides a variety of built-in-animations for toast notifications.

The choice between React toastify and Notistack largely depends on your preferences and requirements.

Best Tips and Practices

  • Install and import the library.

  • Include `<ToastContainer/>` in your app.

  • You can create Toast Triggering using `toast.success`, `toast.error`, etc.

  • Customize styles and use your components.

  • Set `autoClose` or manage closing manually

  • Enhance UX with features like `pauseOnHover`

Final Thoughts on React Toastify

In conclusion, React toastify proves to be a user-friendly, versatile notification library, enhancing user experience by seamlessly handling toast notifications in your React application. Its customizable features, robust documentation and ease of integration makes it a valuable tool for developers seeking an efficient way convey messages to users.

With its rich set of options, React toastify empowers developers to create informative and visually appealing notifications, contributing to an overall polished and engaging UI.

PureCode.ai can cater for your code development process. It will save you valuable time and effort on a project by providing customized, and ready-to-use components which will allow you to prioritize more important and thought-intensive tasks to speed up the development of your user interface.

Shadrach Abba

Shadrach Abba