How to create a toast notification in React
Today we’ll show you how to create a toast notification in React. Here we will use the npm package to handle the toast notification using ReactJS.
You'll also find useful articles which have been made using the npm package.
Steps to create a toast notification in React
1. Create a react application
First of all we’ll create a startup react application using the `create-react-app` npm package. Run the following command to create a react app.
npx create-react-app toast-notification-react
2. Add npm dependency
To implement toast notification, we’ll use the react-toastify npm package. Run the following command to install the npm dependency.
npm i react-toastify
3. Add toast notification in component
After installing the npm package, we have to import the `react-toastify` package and their css. We have to add the `ToastContainer` to notify via toast message. Here we have added the five different buttons to notify the different types of the message.
import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App() {
const toastInfo = () => toast.info('Clue Mediator - The way to write your code');
const toastSuccess = () => toast.success('Clue Mediator - The way to write your code');
const toastWarn = () => toast.warn('Clue Mediator - The way to write your code');
const toastError = () => toast.error('Clue Mediator - The way to write your code');
const toastDark = () => toast.dark('Clue Mediator - The way to write your code');
return (
<div class="App">
<h3>Toast Notification in React - <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
<button class="btn" onclick={toastInfo}>Notify - Info</button>
<button class="btn" onclick={toastSuccess}>Notify - Success</button>
<button class="btn" onclick={toastWarn}>Notify - Warn</button>
<button class="btn" onclick={toastError}>Notify - Error</button>
<button class="btn" onclick={toastDark}>Notify - Dark</button>
<toastcontainer position="bottom-right" autoclose={5000} hideprogressbar={false} newestontop={false} closeonclick="" rtl={false} pauseonfocusloss="" draggable="" pauseonhover="">
</toastcontainer></div>
);
}
export default App;
Check out the documentation of the react-toastify npm package.
4. Output
Run the application and check out the output in the browser.
Output - How to create a toast notification in React - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!!