by Sai gowtham

React toast notifications tutorial

Home » react » React toast notifications tutorial
React toast notifications tutorial

In this tutorial, we are going to learn about how to add toast notifications to our react app using the react-toastify library.


Let’s install the react-toastify library to our react app.

Run the below command in your terminal.

npm i react-toastify

Adding toast notifications


import React from "react";
import { ToastContainer, toast } from "react-toastify";import "react-toastify/dist/ReactToastify.css";
function App() {
  function Notify() {    toast("You clicked the button");  }
  return (
    <div className="App">
      <ToastContainer />      <button onClick={Notify}>Run toast</button>

export default App;

In the above code, we first imported a toast method, <ToastContainer> component from the react-toastify and also ‘ReactToastify.css’ file for the default styling.

  • toast( ) : The toast method takes the content as a first argument, it means what content we need to see during the toast notification (like we added You clicked the button in the above code).
  • ToastContainer: To render the toast we need to add a ToastContainer component in our app.


Changing toasts position

By default toasts will be shown on top-right position of your browser, we can change the toast position by adding a second argument to the toast method.

  function Notify() {
    toast("You clicked the button",{
        //toast is positioned on bottom right        position: "bottom-right"

These are the other available position values.


Closing toasts or disable

By default, toasts will be auto closed after 5000 milliseconds (5 seconds), we can delay the toasts closing time by adding an autoClose property to the toast method.

  function Notify() {
    toast("You clicked the button",{
        position: "bottom-right",
        //toast will be closed after 10 seconds
        autoClose: 10000    });

We can also disable the auto close by setting autoClose property to false.

  function Notify() {
    toast("You clicked the button",{
        position: "bottom-right",
        autoClose: false    });

You can find more information about react-toastify library in GitHub.