A toastifier is used to show the message banner on the website, for example showing form submissions, warning Messages, and etc.)
To set-up the toastifier on the web page
Step 1. First, you need to install the react-toastify package in your React project. Use npm or yarn to add it as a dependency:
npm install react-toastify;
Step 2: Import react-toastify in Your Project
Import the necessary components and CSS styles from “react-toastify" in your main application file or the file where you want to use the toasts. Typically, this would be your App.jsorindex.js file.
// Import the ToastContainer and the CSS
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
Step 3: Add the ToastContainer Component
The ToastContainer component is necessary to render the toasts. It should be added to your component tree, typically near the root of your application. This component will handle displaying the toasts.
function App() {
return (
<div className="App">
{/* Your other components */}
<ToastContainer />
</div>
);
}
export default App;
Step 4: Trigger Toasts in Your Application
Use the toast function to trigger toasts in your application. You can call this function whenever you want to display a toast notification. Here is an example of how to use it:
import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App() {
const notify = () => toast("Wow so easy!");
return (
<div className="App">
<button onClick={notify}>Notify!</button>
<ToastContainer />
</div>
);
}
export default App;
Step 5: Customize Toasts (Optional)
react-toastify allows you to customize the appearance and behavior of your toasts. You can pass options to the toast function to customize individual toasts or configure theToastContainer to set global defaults.
const notify = () => {
toast.success("Success message!", {
position: toast.POSITION.TOP_RIGHT,
autoClose: 5000, // 5 seconds
});
toast.error("Error message!", {
position: toast.POSITION.BOTTOM_LEFT,
autoClose: false, // Disable auto-close
});
};