I have MUI dialog which when I clickAway outside it can’t be removed. I want to add a shake effect or any effect to the dialog when the user clicks away so the user knows that clicking away is blocked. Besides, I want to prevent the user to use the Esc button to remove the dialog too.
The suggested answer could solve my question partially, just the Esc button using disableEscapeKeyDown attribute but not the rest of my question as disableBackdropClick can’t be applied.
This is my code. The clickAway is applied in the handleClose function. But I want to add an effect so that the user knows that clicking away isn’t allowed and prevent from using the Esc button to remove the dialog. Any suggestions? I couldn’t find any solution atm. Thanks
export const StatusModalFail = (): ReactElement => {
const [open, setOpen] = useState(true);
const handleClose = (event, reason) => {
if (reason !== 'backdropClick') {
setOpen(false);
}
};
const handleCloseButton = () => {
setOpen(false);
};
return (
<Stack
justifyContent="center"
alignItems="center"
>
<Dialog
open={open}
PaperProps={{
sx:{
width: '100%',
maxWidth: '500px!important',
height:'100%',
maxHeight:'250px!important',
},
}}
onClose={handleClose}
>
<DialogContent>
<Box
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<CrossIcon
style={{
color: '#fa6757',
width: 48,
height: 48,
padding: 30,
}}
/>
</Box>
2
Answers
You can prevent the MUI Dialog from closing when pressing the Esc button by setting the
disableEscapeKeyDown
prop totrue
. To add a shake effect when the user clicks away, you can create a custom backdrop component to handle click events and apply the shake effect. Here’s how you can modify your code:keyframes
:Backdrop
component:Dialog
component to use theCustomBackdrop
component, remove theonClose
prop, and set thedisableEscapeKeyDown
prop totrue
:Now, the Dialog will have a shake effect when clicking away, and the Esc button will not close it.
This is example on how you can do it. I provide the codesanbox here:
https://codesandbox.io/s/hardcore-wing-0mvnqc?file=/demo.js
create new state to handle when you need to shake/animate the dialog
const [shake, setShake] = React.useState(false);
in handleClose function:
shake
state as a prop to your dialog componentshake
state inside thestyled
dialog.MuiDialog-container
to apply the animation:keyframe example here (you can customize it as you need)
and you good to go.