I created a custom Alert as shown below, but when I add Snackbar, it is not displaying. Here is the part that I changed, the rest is the same:
AlertPopup:
const AlertPopup = () => {
const { text, type } = useAlert();
if (text && type) {
return (
// when I use this, the message is displayed
// <Alert variant="filled" severity={type} sx={{}}>
// {text}
// </Alert>
// when I use this, the message is NOT displayed
<Stack spacing={2} sx={{ width: '100%' }}>
<Snackbar autoHideDuration={6000}>
<Alert variant="filled" severity={type} >
{text}
</Alert>
</Snackbar>
</Stack>
);
} else {
return <></>;
}
};
Here is the other parts of the implementation. I did not changed other parts (AlertContext
and useAlert
classes) as there is not specific component for Alert:
So, what is missing with this implementation?
The visibility of the Material UI Snackbar is controlled by the open property. Typically, some change in the state of your component would trigger the display of the Snackbar. See the basic example from the docs.
Your code could be updated like this:
const AlertPopup = () => {
const [ open, setOpen ] = React.useState( false );
const { text, type } = useAlert();
React.useEffect( () => {
// Test for some condition that triggers the display of the Snackbar.
if ( <Snackbar should be displayed> ) {
setOpen( true );
}
// Dependencies array: see https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
}, [ <Dependencies array: includes value(s) used by the effect for the test condition> ] );
if (text && type) {
return (
// when I use this, the message is displayed
// <Alert variant="filled" severity={type} sx={{}}>
// {text}
// </Alert>
// when I use this, the message is NOT displayed
<Stack spacing={2} sx={{ width: '100%' }}>
<Snackbar open={open} autoHideDuration={6000}>
<Alert variant="filled" severity={type} >
{text}
</Alert>
</Snackbar>
</Stack>
);
} else {
return <></>;
}
};