Here is the step-by-step guide to implementing snackbar or toast notification in React:
Step 1: Create a new React project
To create a brand new React project, we will use the Vite bundler, which is effective.
Type the below command:
npm create vite@latest new-app -- --template react
After creating a new project folder, “new-app,” go inside that folder:
cd new-app
Install the React dependencies using the below command:
npm install
It will install all the project-related dependencies.
Step 2: Installing Material UI
You need to install the @mui/material, @emotion/react, and @emotion/styled libraries using this command:
npm install @mui/material @emotion/react @emotion/styled
Modify the src/main.jsx file like this:
// main.jsx import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App.jsx"; ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <App /> </React.StrictMode> );
Step 3: Creating a snackbar component
We need to create a reusable snackbar component to manage notifications. This component is responsible for handling the state for displaying the Snackbar.
We need to add prop types validation using the prop-types library. Install the prop-types using the below command:
npm install prop-types
Create a new component called “SnackbarNotification.jsx” inside the “src” folder and add the below code:
// SnackbarNotification.jsx import { Snackbar, Alert } from "@mui/material"; import PropTypes from "prop-types"; const SnackbarNotification = ({ open, handleClose, message, severity }) => { return ( <Snackbar open={open} autoHideDuration={4000} onClose={handleClose}> <Alert onClose={handleClose} severity={severity} sx={{ width: "100%" }}> {message} </Alert> </Snackbar> ); }; SnackbarNotification.propTypes = { open: PropTypes.bool.isRequired, handleClose: PropTypes.func.isRequired, message: PropTypes.string.isRequired, severity: PropTypes.oneOf(["error", "warning", "info", "success"]).isRequired, }; export default SnackbarNotification;
In this code, we imported Snackbar and Alert components from the @mui/material library.
We also imported the PropTypes library to type-check the props passed to the React component.
Basically, we defined the SnackbarNotification functional component that accepts four props (open, handleClose, message, and severity) and uses PropTypes to enforce type-checking for these props.
This SnackbarNotification functional component returns the Snackbar component from Material UI, which displays a brief message at the bottom of the screen.
The Snackbar component accepts open, autoHideDuration, and onClose properties.
We also used the Alert component, another component from Material UI, typically used to display a message with a specific severity (like error, warning, info, or success). We will display a simple success notification in green.
Step 4: Using the SnackbarNotification component
We created a SnackbarNotification component but have not registered it in our React application.
Update the src/App.jsx file to import the SnackbarNotification component and gather all the pieces of our code.
// App.jsx import { useState } from "react"; import SnackbarNotification from "./SnackbarNotification"; import { Button } from "@mui/material"; function App() { const [snackbarOpen, setSnackbarOpen] = useState(false); const [snackbarMessage, setSnackbarMessage] = useState(""); const [snackbarSeverity, setSnackbarSeverity] = useState("success"); const handleSnackbarOpen = (message, severity) => { setSnackbarMessage(message); setSnackbarSeverity(severity); setSnackbarOpen(true); }; const handleSnackbarClose = (event, reason) => { if (reason === "clickaway") { return; } setSnackbarOpen(false); }; const handleButtonClick = () => { handleSnackbarOpen("This is a success message!", "success"); }; return ( <div> <Button variant="contained" onClick={handleButtonClick}> Show Success Snackbar </Button> <SnackbarNotification open={snackbarOpen} handleClose={handleSnackbarClose} message={snackbarMessage} severity={snackbarSeverity} /> </div> ); } export default App;
Inside the App component, we defined three functions:
- handleSnackbarOpen(): It shows the Snackbar with a specific message and severity.
- handleSnackbarClose(): It closes the Snackbar.
- handleButtonClick(): It demonstrates showing a Snackbar.
When we click on the “Show success Snackbar” button, the handleButtonClick() function is called, and we change the state of snackbarOpen, snackbarMessage, and snackbarOpen variables. These changes in state variables will display the toast notification to users.
Save this file, go to the terminal, and start the development server using this command:
npm run dev
Go to this URL: http://localhost:5173/
You will see a screen like below image:
If you click on the “SHOW SUCCESS SNACKBAR” button, it will display a toast notification like this:
That’s all!