I am trying to position a Snackbar to the top right with some top: customization but I not able to set it correctly.
Here is my attempt:
import React from "react";
import { Snackbar, Alert } from "@mui/material";
import { styled } from "@mui/material/styles";
const StyledSnackbar = styled(Snackbar)(({ theme, props }) => ({
"& MuiSnackbar-root": {
top: theme.spacing(15),
},
}));
export default function Notification(props) {
const { notify, setNotify } = props;
return (
<StyledSnackbar
open={notify.isOpen}
autoHideDuration={3000}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
>
<Alert severity={notify.type}>{notify.message}</Alert>
</StyledSnackbar>
);
}
Then I tried
const StyledSnackbar = styled(Snackbar)(() => ({
"& MuiSnackbar-root": {
top: "100px",
},
}));
But it's still not working, the Snackbar is fixed to top/right
Here's my approach which seems to work nicely with MUI v5. I've overriden the MuiSnackbar-root class to have a different bottom value. You could do the same with top, left and right as you desire.
<Snackbar
open={open}
autoHideDuration={timeout * 1000}
onClose={handleClose}
sx={{
'&.MuiSnackbar-root': { bottom: '50px' },
}}
>
<SnackbarContent
sx={{ backgroundColor: '#bb4420' }}
message={message}
action={action}
/>
</Snackbar>
Doesn't look like Snackbar
component provides any means of precise positioning, apart from the fairly limited anchorOrigin
.
It's root element uses position: fixed
hence wrapping it with properly styled <Portal>
doesn't help either.
Source code of the component responsible for positioning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With