💨

Material UI で Chakra ui のtoastを再現する!

2024/08/30に公開

useSnackBarコンポーネント

import React, { useState } from "react";
import { CustomSnackBar } from "~/app/_components/CustomSnackBar";

export const useSnackBar = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [severity, setSeverity] = useState<"success" | "error">("success");
  const [message, setMessage] = useState("");

  const openSnackBar = ({
    severity,
    message,
  }: {
    severity: "success" | "error";
    message: string;
  }) => {
    setSeverity(severity);
    setMessage(message);
    setIsOpen(true);
  };

  const SnackBar = (
    <Snackbar
      open={isOpen}
      autoHideDuration={3000}
      anchorOrigin={{ vertical: "top", horizontal: "center" }}
      onClose={() => setIsOpen(false)}
    >
      <Alert
        severity={severity}
        variant="filled"
        sx={{
          width: "100%",
          fontSize: "18px",
          color: "white",
        }}
      >
        {message}
      </Alert>
    </Snackbar>
  );
  return { openSnackBar, SnackBar };
};

使い方

export const Sample = () => {
  const { openSnackBar, SnackBar } = useSnackBar();

  return (
    <>
      {SnackBar}
      ...
    </>
  );
}

Discussion