React 18 Material UI Alert Box Component Examples Tutorial

Last Updated on by in React JS

React Material UI Alert box example. In this tutorial, you will learn how to create a user-friendly alert box component in React JS with the help of React Material UI library in a function component from scratch.

We will show you how to build a basic alert box with different sizes and colours.

Not only but also, we will show you how to use various properties provided by React MUI to customize the alert component in React js application.

An alert dialog box is very useful in UI; It is a type of unique dialog box that is mainly used to display in a graphical user interface when something unanticipated happens that requires prompt user action.

An alert displays a short and descriptive message, especially when something unexpected occurs.

The alert box shows an important message that informs users to take certain actions. It grabs users’ attention in a way that lures the user’s attention without interrupting the user’s task.

How to Create Alert Box Component in React with Material UI

  • Step 1: Build New Project
  • Step 2: Install React Material UI Package
  • Step 3: Create Function Class
  • Step 4: Create Alert Box in React
  • Step 5: Alert Box with Description
  • Step 6: Alert Box with Close and Undo Button
  • Step 7: Add Icon in Alert Box
  • Step 9: Register Component in App Js
  • Step 10: Start React Application

Build New Project

If you haven’t created the new project; worry not, we have mentioned the “npx Create React App” command after you execute the following command a new project will be created.

npx create-react-app react-blog-app

Enter into the project, after the app is installed.

cd react-blog-app

Install React Material UI Package

React Material UI is easy to install and it can be installed with just a single command. You need to perform the following command from the terminal app to install the required packages.

npm i @mui/material @emotion/react @emotion/styled @fontsource/roboto --legacy-peer-deps

React MUI is installed and it will be ready to create the flawless UI components. Make sure to add the given fonts and CSS in the App.css file.

@import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap");
@import "@fontsource/roboto/300.css";
@import "@fontsource/roboto/400.css";
@import "@fontsource/roboto/500.css";
@import "@fontsource/roboto/700.css";

Create Function Class

React allows class and function components to build functionalities with boundless flexibility.

We are going to take function component approach, hence we will create components/ folder inside the src directory. Also, we will make the AlertBox.js file with given code.

import React from 'react'
function AlertBox() {
  return (
    <div>ToggleSwitch</div>
  )
}
export default AlertBox

Create Alert Box in React

Let us begin by creating a simple success alert box. Inside the function, the class import the Alert and Stack modules and define the alert component in return methods.

The alert box comes with four severity grades that set a unique icon and color.

Add following code in the components/AlertBox.js file.

import * as React from "react";
import Alert from "@mui/material/Alert";
import Stack from "@mui/material/Stack";
export default function AlertBox() {
  return (
    <Stack sx={{ width: "100%" }} spacing={2}>
      <Alert severity="error">This is an error alert — check it out!</Alert>
      <Alert severity="warning">This is a warning alert — check it out!</Alert>
      <Alert severity="info">This is an info alert — check it out!</Alert>
      <Alert severity="success">This is a success alert — check it out!</Alert>
    </Stack>
  );
}

Alert Box with Description

You can pretty much easily define description in alert in React. Also, we can add the AlertTitle component rigorously to show a formatted title above the content.

import * as React from 'react';
import Alert from '@mui/material/Alert';
import AlertTitle from '@mui/material/AlertTitle';
import Stack from '@mui/material/Stack';
export default function AlertBox() {
  return (
    <Stack sx={{ width: '100%' }} spacing={2}>
      <Alert severity="error">
        <AlertTitle>Error</AlertTitle>
        This is an error alert — <strong>check it out!</strong>
      </Alert>
      <Alert severity="warning">
        <AlertTitle>Warning</AlertTitle>
        This is a warning alert — <strong>check it out!</strong>
      </Alert>
      <Alert severity="info">
        <AlertTitle>Info</AlertTitle>
        This is an info alert — <strong>check it out!</strong>
      </Alert>
      <Alert severity="success">
        <AlertTitle>Success</AlertTitle>
        This is a success alert — <strong>check it out!</strong>
      </Alert>
    </Stack>
  );
}

Alert Box with Close and Undo Button

You usually want to hide the alert after showing the message to users.

We seldom programmatically hide the alert box, or you can add the close button in the alert.

An alert might have an action, like a close or undo button. It manifests after the message or at the end of the alert.

import * as React from 'react';
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
export default function AlertBox() {
  return (
    <Stack sx={{ width: '100%' }} spacing={2}>
      <Alert onClose={() => {}}>This is a success alert — check it out!</Alert>
      <Alert
        action={
          <Button color="inherit" size="small">
            UNDO
          </Button>
        }
      >
        This is a success alert — check it out!
      </Alert>
    </Stack>
  );
}

Add Icon in Alert Box

Alert comes with custom props that help you make the icon-adding process facile.

The icon prop permits you to set an icon at the beginning of the alert component.

import * as React from 'react';
import Alert from '@mui/material/Alert';
import CheckIcon from '@mui/icons-material/Check';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import Stack from '@mui/material/Stack';
export default function AlertBox() {
  return (
    <Stack sx={{ width: '100%' }} spacing={2}>
      <Alert icon={<CheckIcon fontSize="inherit" />} severity="success">
        This is a success alert — check it out!
      </Alert>
      <Alert
        iconMapping={{
          success: <CheckCircleOutlineIcon fontSize="inherit" />,
        }}
      >
        This is a success alert — check it out!
      </Alert>
      <Alert icon={false} severity="success">
        This is a success alert — check it out!
      </Alert>
    </Stack>
  );
}

Register Component in App Js

We have successfully created the Switch button component; it won’t show on the browser unless we inject it inside the App.js main component file.

import React from "react";
import AlertBox from "./components/AlertBox";
function App() {
  return (
    <div>
      <h2>React Material UI Custom Alert Box Example</h2>
      <AlertBox />
    </div>
  );
}
export default App;

Start React Application

Once the app is ready, the most important task after that is to serve the React project.

We can do it very easily by running the given command.

npm start

Above command will print the application serving path on the terminal that you can use to view the app.

http://localhost:3000

React Material UI Alert Box Component Examples Tutorial

Conclusion

In this tutorial, we have learned how to implement an alert box in a React functional component.

To create the alert component in React, we installed and used React material UI from the absolute bottom.

We hope we have given clear instructions which will help you to add and use the alert box in the React app.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.