Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mui V5 Snackbar custom position

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

like image 387
Moe Avatar asked Sep 02 '25 10:09

Moe


2 Answers

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>
like image 82
Alex Avatar answered Sep 04 '25 01:09

Alex


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.

like image 25
Alex M Avatar answered Sep 04 '25 01:09

Alex M