简体   繁体   中英

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

I finally figured it out, but I am not sure if this is the best way implementing it. please let me know your thoughts? and if there is a better way of doing it.

import React from "react";
import { Snackbar, Alert } from "@mui/material";

import { styled } from "@mui/material/styles";

const StyledSnackbar = styled((props) => <Snackbar {...props} />)(
  ({ theme }) => ({
    "& .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>
  );
}

I use this in my stylesheet.css

.MuiSnackbar-anchorOriginTopCenter {
  top: 150px !important;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM