Learn React toastify with example


react alert notifications in app are used to display alert notifications with user customized message Some of the examples, are success message, record is added, error message - duplicate record found,warning and informational messages.

Other versions available:

In this tutorials, You’ll learned how to implement alert notifications with react-toastify npm library. react-toastify is popular toast/alert notification for React project.

This npm library has many features included.

  • Opensource and easy to configure and customize
  • Programmatically control notifications
  • Customize the styles and display location like top,left,bottom
  • progress bar included
  • Package size is very less.

react-toastify tutorial application

First, Let’s create a new react application using create-react-app command.

npx create-react-app react-toast-tutorial

This creates a react-toast-tutorial project and creates all required files to run a project,installs depedencies

Next, Go to application root folder and run npm run start command.

npm run start

This starts application in browser and able to access with localhost:3000

add toastify npm dependency

Go to application folder, run the below command to install the react-toastify npm dependency

npm install --save react-toastify

This updates package.json and install the dependency to node_modules folder in application

 "dependencies": {
    "react": "17.0.0",
    "react-dom": "17.0.0",
    "react-toastify": "^6.2.0"
  }

Secondly, add required css files to application

Adding ReactToastify.css to existing application

import react-toastify css into react component

It provides css styles that you need to import into component

import 'react-toastify/dist/ReactToastify.css';

Add ToastContainer one time in global component.

ToastContainer and toast are two classes imported into your app to display toast notification.

 import { toast, ToastContainer } from "react-toastify";

ToastContainer is a container for application that you need to include root component. This must be loaded into DOM tree. However, These is not required to add it in every component,

      <ToastContainer closeButton={false} position="bottom-right" />

toast configure method:

toast.configure() has to call in Root component and it is one time process

  toast.configure();

This can configure configuration object which is an object of configuration

This can be used to configure how toast popup customization

toast.configure({
  autoClose: 10000,
  draggable: true,
});

Next, popup can be displayed using toast object


Toast.success/error/info/warn/dark/default(message,optionalobject)

An example, to configure success popup displayed in top right position

  toast.success("Success message", {
    position: "top-right",
    pauseOnHover: true,
    draggable: false,
    progress: undefined,
  });

optional object contains below parameters

  • position values top-left,top-right,top-center, bottom-left,bottom-right,bottom-center
  • draggable popup is draggable or not,true/false
  • progress is to configure progress bar

Dismiss toast programmatically

toast.dismiss() is to close the toast using code.

Basic toast notification example

In Root component, import and configure ToastContainer in application root

App.js code:

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

export default function App() {
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <BasicToast />
      <ToastContainer closeButton={false} position="bottom-right" />
    </div>
  );
}

let’s create toast component for example

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import { toast, Zoom } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

class BasicToast extends Component {
  constructor() {
    super();
  
  }

  showError = () => {
    toast.error("ERROR Notification");
  };

  showSuccess = () => {
    toast.success("Success Notification");
  };

  showInfo = () => {
    toast.info("Info Notification");
  };

  showWarn = () => {
    toast.warn("Warn Notification");
  };

  render() {
    return (
      <div>
        <div>
          <span>
            <button onClick={this.showError}>Error </button>
          </span>
          <span>
            <button onClick={this.showSuccess}>Success </button>
          </span>
          <span>
            <button onClick={this.showInfo}>Info </button>
          </span>
          <span>
            <button onClick={this.showWarn}>Warn </button>
          </span>
        </div>
      </div>
    );
  }
}

export default BasicToast;

Now, Run the project and rendered output :

React toast notification example

alert notifications for API result

Assume, callAPI is an async method which return the response from API for success result,error response for an API error.

In promise then method, toast.dismiss closes the toast if already displayed to browser calling toast.error for error result toast.success for success result

callAPI().then(response => {
    if (response.error) {
        toast.dismiss();
        toast.error("ERROR while calling API");
    } else {
        toast.dismiss();
        toast.success("API SUCCESS Done");
        }
});

Conclusion

This post talks about basic toast component.

Similar Posts