Today we are going to learn how to use a Custom Alert Dialog in React.
To create this Dialog, I will use the Mui library (https://mui.com/)
First, we need to install it:
npm install @mui/material @emotion/react @emotion/styled
Now let’s create our component, which we’ll call CustomAlert.js
import React, { useState, useEffect } from 'react'; import Button from '@mui/material/Button'; import Dialog from '@mui/material/Dialog'; import DialogActions from '@mui/material/DialogActions'; import DialogContent from '@mui/material/DialogContent'; import DialogContentText from '@mui/material/DialogContentText'; import DialogTitle from '@mui/material/DialogTitle'; let setOpenExt; let setParamsExt; const AlertDialog = () => { const [open, setOpen] = useState(false); const [alertParams, setAlertParams] = useState({ customTitle: '', customContent: '', customCancelText: '', customAcceptText: '', displayCancelButton: true, onCancel: () => {}, onAccept: () => {}, }); useEffect(() => { setParamsExt = (params) => { setAlertParams(params); }; setOpenExt = setOpen; }, []); const handleClose = () => { setOpen(false); if (alertParams.onCancel) { alertParams.onCancel(); } }; const handleAgree = () => { handleClose(); if (alertParams.onAccept) { alertParams.onAccept(); } }; return ( <React.Fragment> <Dialog open={open} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" PaperProps={{ style: { maxWidth: '400px', width: '100%', }, }} > <DialogTitle id="alert-dialog-title"> {alertParams.customTitle} </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> {alertParams.customContent} </DialogContentText> </DialogContent> <DialogActions> {alertParams.displayCancelButton && ( <Button onClick={handleClose}> {alertParams.customCancelText} </Button> )} <Button onClick={handleAgree} autoFocus> {alertParams.customAcceptText 'Accept'} </Button> </DialogActions> </Dialog> </React.Fragment> ); }; export default AlertDialog; export const showAlert = (params) => { setParamsExt(params); setOpenExt(true); };
To use our alert, you can do the following:
import React from 'react'; import AlertDialog, { showAlert } from './CustomAlert'; // Adjust the path according to your project structure const MyScreen = () => { const handleShowAlert = () => { showAlert({ customTitle: 'Alert Title', customContent: 'Alert Content', customCancelText: 'Cancel', customAcceptText: 'Accept', displayCancelButton: true, onCancel: () => { console.log('Cancelled action'); }, onAccept: () => { console.log('Accepted action'); }, }); }; return ( <div> <AlertDialog/> <h1>My Screen</h1> <button onClick={handleShowAlert}>Show Alert</button> {/* You can add more screen content here */} </div> ); }; export default MyScreen;
Remember to import the alert:
import AlertDialog, { showAlert } from './CustomAlert'; // Make sure to adjust the correct path
Then, create the component on the