How to use Alert Component in React JS?
React JS is a widely used JavaScript library for constructing user interfaces. It simplifies web development by adopting a component-based approach, facilitating the creation of engaging and responsive applications. An often-encountered need in applications is the presentation of alerts or notifications to users.
Prerequisites:
Approach to use Alert Component:
In this React app, we’re using Material-UI to display alert messages. First, we import the needed parts from React and Material-UI. Then, we create a special function called `Alert` to customize how the alerts look. In the main part of our app, we use this `Alert` function to show different messages for success and errors. This keeps our code organized and helps us handle alerts easily.
Steps to Create the React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
npm install @material-ui/lab
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"@material-ui/core": "^4.12.4",
"@material-ui/icons": "^4.11.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Now write down the following code in the App.js file.
Javascript
import React from "react" ; import MuiAlert from "@material-ui/lab/Alert" ; function Alert(props) { return <MuiAlert elevation={6} variant= "filled" {...props} />; } export default function App() { return ( <div> <h4>How to use Alert Component in ReactJS?</h4> <Alert severity= "success" >Sample Success Message</Alert> <Alert severity= "error" >Sample Error Message</Alert> </div> ); } |
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.