Introduction
This article demonstrates how to create a toast notification using reactjs.
Prerequisites
- Basic knowledge of ReactJS
- Visual Studio Code
- Node and NPM installed
Toast Notification in React
To achieve this we need to install a package 'react-toastify' to render the toast notification in react and can import it and use it in our sample project.
Step 1. Create a React.js Project
Let's create a new React project by using the following command.
npx create-react-app toast-notification-app
Step 2. Install NPM dependencies
npm i react-toastify
Step 3. Create a Component for toast notification
Create a folder for toast notification and inside it create a component, 'toastNotification.js'. Add the following code to this component.
import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function ToastNotification() {
const toastDark = () => toast.dark('This is Toast Notification for Dark');
const toastInfo = () => toast.info('This is Toast Notification for Info');
const toastSuccess = () => toast.success('This is Toast Notification for Success');
const toastWarn = () => toast.warn('This is Toast Notification for Warn');
const toastError = () => toast.error('This is Toast Notification for Error');
return (
<div className="App">
<h3>Toast Notification in React </h3>
<button className="btn" onClick={toastDark}>Toast Notification for - Dark</button>
<button className="btn" onClick={toastInfo}>Toast Notification for - Info</button>
<button className="btn" onClick={toastSuccess}>Toast Notification for - Success</button>
<button className="btn" onClick={toastWarn}>Toast Notification for - Warn</button>
<button className="btn" onClick={toastError}>Toast Notification for - Error</button>
<ToastContainer
position="top-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
/>
</div>
);
}
export default ToastNotification;
Step 4
Add the below code in App.js file
import './App.css';
import ToastNotification from './toastNotification/toastNotification';
function App() {
return (
<ToastNotification/>
);
}
export default App;
Step 5. Output
Now, run the project by using the 'npm start' command, and check the result.
Summary
In this article, we have discussed how we can create a toast notification functionality in reactjs.