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.
1 | 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.
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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 className="App"> <h3>Toast Notification in React - <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> <button className="btn" onClick={toastInfo}>Notify - Info</button> <button className="btn" onClick={toastSuccess}>Notify - Success</button> <button className="btn" onClick={toastWarn}>Notify - Warn</button> <button className="btn" onClick={toastError}>Notify - Error</button> <button className="btn" onClick={toastDark}>Notify - Dark</button> <ToastContainer position="bottom-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover /> </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.
That’s it for today.
Thank you for reading. Happy Coding..!!