How To Display Alert Message In React.js

Introduction

In this article, I will guide you through the process of adding an alert message in React.js

Prerequisites of React

  • Familiarity with HTML, and JavaScript.
  • node.js installed
  • Basic knowledge of React JS
  • Visual Studio Code

Create React Project

To create a React app, use the following command in the terminal.

npx create-react-app matui

Open the newly created project in Visual Studio Code, and install Material-UI; run the following command in your React project's root directory.

npm install @material-ui/core

Now right-click on the src folder and create a new component named 'Alertdemo.js'. We will create a simple modal popup using material UI. Import the following component from Material UI in the Alertdemo.js file.

import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';

Now, add the following code in the Alertdemo.js file.

import React from 'react'
import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';
function Alertdemo() {
  return (
    <Stack sx={{ width: '50%' }} spacing={2}>
      <Alert variant="outlined" severity="error">
        This is an error alert — check it out!
      </Alert>
      <Alert variant="outlined" severity="warning">
        This is a warning alert — check it out!
      </Alert>
      <Alert variant="outlined" severity="info">
        This is an info alert — check it out!
      </Alert>
      <Alert variant="outlined" severity="success">
        This is a success alert — check it out!
      </Alert>
      <Alert variant="filled" severity="error">
        This is an error alert — check it out!
      </Alert>
      <Alert variant="filled" severity="warning">
        This is a warning alert — check it out!
      </Alert>
      <Alert variant="filled" severity="info">
        This is an info alert — check it out!
      </Alert>
      <Alert variant="filled" severity="success">
        This is a success alert — check it out!
      </Alert>
    </Stack>
  )
}

export default Alertdemo

Now, import the Alertdemo component in the src/App.js file.

import './App.css';
import Alertdemo from './Alertdemo'
function App() {
  return (
    <div className="App">
      <Alertdemo/>
    </div>
  );
}

export default App;

Run the project using the 'npm start' command and check the result.

Summary

In this article, we learned how to add an alert message in React.js