- Published on
Display Material-UI Alert Based on Axios Response in React.js
- Authors
- Name
- Ripal & Zalak
How to Display Material-UI Alert Based on Axios Response in React.js
If you're using alert(response.data.result)
and want a more aesthetic notification system, then Material-UI Alerts are a great alternative. This guide will show you how to display an alert dynamically based on an axios.post
request response.
Step-by-Step Solution
1. Install Material-UI Components
If you haven't installed Material-UI, run the following command:
npm install @mui/material @mui/lab @emotion/react @emotion/styled
2. Implement Alert Handling in a React Component
Modify your component to store the alert message in state and conditionally render the Material-UI Alert.
Example Code:
import React, { useState } from 'react'
import axios from 'axios'
import { Alert, Button, Modal, Box } from '@mui/material'
function Test() {
const [alert, setAlert] = useState({ show: false, message: '', severity: 'success' })
const [modalOpen, setModalOpen] = useState(false)
const saveData = async () => {
try {
const response = await axios.post('/API', { param1: 'value1' })
if (response.data.success) {
setAlert({ show: true, message: response.data.result, severity: 'success' })
} else {
setAlert({ show: true, message: response.data.result, severity: 'error' })
}
} catch (error) {
setAlert({ show: true, message: 'An error occurred!', severity: 'error' })
}
}
return (
<div>
{/* Material-UI Alert */}
{alert.show && (
<Alert severity={alert.severity} onClose={() => setAlert({ show: false })}>
{alert.message}
</Alert>
)}
{/* Modal */}
<Modal open={modalOpen} onClose={() => setModalOpen(false)}>
<Box sx={{ width: 400, bgcolor: 'white', p: 3, m: 'auto', mt: 10 }}>
<Button onClick={saveData}>Save</Button>
</Box>
</Modal>
{/* Button to Open Modal */}
<Button variant="contained" onClick={() => setModalOpen(true)}>
Open Modal
</Button>
</div>
)
}
export default Test
Explanation
useState
for alert: Stores alert message & severity (success
,error
, etc.).setAlert
updates alert dynamically after anaxios.post
request.- Conditionally render
<Alert>
: It disappears when closed. - Material-UI
<Modal>
: Shows a button inside a modal.
FAQs
1. How to Show Alert Inside Modal?
Wrap <Alert>
inside <Modal>
with an absolute position.
<Modal open={modalOpen} onClose={() => setModalOpen(false)}>
<Box sx={{ position: 'relative', p: 2, bgcolor: 'white' }}>
{alert.show && <Alert severity={alert.severity}>{alert.message}</Alert>}
<Button onClick={saveData}>Save</Button>
</Box>
</Modal>
2. Can I Customize Alert Styling?
Yes! Use the sx
prop for custom styles:
<Alert severity="warning" sx={{ fontSize: '18px', fontWeight: 'bold' }}>
Warning Message
</Alert>
3. How to Add a Close Button in Alert?
Use onClose
to allow manual dismissal:
<Alert severity="info" onClose={() => setAlert({ show: false })}>
Info Message
</Alert>