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.
Installation
Let’s install the react-toastify library to our react app.
Run the below command in your terminal.
npm i react-toastifyAdding toast notifications
Example
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>
</div>
);
}
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
contentas a first argument, it means what content we need to see during the toast notification (like we addedYou clicked the buttonin the above code). -
ToastContainer: To render the toast we need to add a
ToastContainercomponent 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.
top-right,
top-center,
top-left
bottom-right,
bottom-center,
bottom-leftClosing 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-toastifylibrary in GitHub.


