How to auto close mui alert in react js?
June 15, 2023Hi Friends 👋,
Welcome To aGuideHub!
To auto close mui alert in React js, you can use this code setTimeout(handleClose, 3000);
. It will auto close mui alert in react js.
Today, I am going to show you, how to auto close mui alert in react js.
Installation
Install the following packages to use mui Alert in react js.
npm
npm install @mui/material @emotion/react @emotion/styled
yarn
yarn add @mui/material @emotion/react @emotion/styled
Table of contents
- Install MUI and create a new React app.
- Import Material-UI alert.
- Use the Alert Component
Step 1: Install MUI and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import Material-UI alert.
After installing MUI
, you have to import your React component. To do this, add the following line to the top of your component file.
import { useState } from 'react';
import { Alert, AlertTitle } from '@mui/material';
Step 3: Use the Alert Component
You can use the Alert
component in your react js. For example, The Alert component is used to display important messages or notifications to users. You can use <Alert>
component make a alert box in react js.
<Alert severity="info" onClose={handleClose}>
<AlertTitle>Auto-Closing Alert</AlertTitle>
This alert will automatically close after 3 seconds.
</Alert>
MUI material auto close mui alert example.
The below code is an example, to auto close mui alert, you need to import Alert
Component. We use the setTimeout
function to call the handleClose
function after a specified period of time (in this case, 3000 milliseconds or 3 seconds).
App.js
import { useState } from 'react';
import { Alert, AlertTitle } from '@mui/material';
function App() {
const [open, setOpen] = useState(true);
const handleClose = () => {
setOpen(false);
};
// Automatically close the alert after 3000 milliseconds (3 seconds)
setTimeout(handleClose, 3000);
return (
<div>
{open && (
<Alert severity="info" onClose={handleClose}>
<AlertTitle>Auto-Closing Alert</AlertTitle>
This alert will automatically close after 3 seconds.
</Alert>
)}
</div>
);
}
export default App;
In the above code example, I have used the @mui/material
component and auto close mui alert in react js.
Check the output of the above code example.
Here, we are provided code sandbox links for the above program auto close mui alert in react js. Then you can use whenever you want and do the changes as per your requirements.
All the best 👍