@mui/material#Snackbar TypeScript Examples

The following examples show how to use @mui/material#Snackbar. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 7 votes vote down vote up
WifiDeviceNotification: FunctionComponent<WifiDeviceNotificationProps> = (
  props
) => {
  const { newNetworkDevices, removeDeviceFromNewList, onDeviceChange } = props;
  const { appStatus } = useAppState();

  return (
    <>
      {appStatus === AppStatus.Interactive &&
        newNetworkDevices.map((dnsDevice) => {
          const handleClose = () => {
            removeDeviceFromNewList(dnsDevice.name);
          };

          return (
            <Snackbar
              key={dnsDevice.name}
              open
              autoHideDuration={6000}
              onClose={handleClose}
            >
              <Alert onClose={handleClose} severity="info">
                New Device {dnsDevice.name} ({dnsDevice.ip})
                <Button
                  size="small"
                  onClick={() => {
                    onDeviceChange(dnsDevice);
                    removeDeviceFromNewList(dnsDevice.name);
                  }}
                >
                  Select
                </Button>
              </Alert>
            </Snackbar>
          );
        })}
    </>
  );
}
Example #2
Source File: Message.tsx    From your_spotify with GNU General Public License v3.0 6 votes vote down vote up
export default function Message() {
  const message = useSelector(selectMessage);
  const [open, setOpen] = useState(false);

  const onClose = useCallback(
    (_: Event | React.SyntheticEvent<any, Event>, reason: SnackbarCloseReason) => {
      if (reason === 'clickaway') {
        return;
      }
      setOpen(false);
    },
    [],
  );

  useEffect(() => {
    setOpen(true);
  }, [message]);

  if (!message) {
    return null;
  }

  return (
    <Snackbar
      open={open}
      autoHideDuration={2000}
      onClose={onClose}
      anchorOrigin={{ horizontal: 'center', vertical: 'top' }}>
      <Alert onClose={() => setOpen(false)} level={message.level} message={message.message} />
    </Snackbar>
  );
}
Example #3
Source File: SnackbarProvider.tsx    From airmessage-web with Apache License 2.0 6 votes vote down vote up
export default function SnackbarProvider(props: {children: React.ReactNode}) {
	const [open, setOpen] = React.useState<boolean>(false);
	const [data, setData] = React.useState<SnackbarData>();
	
	function displaySnackbar(data: SnackbarData) {
		setOpen(true);
		setData(data);
	}
	
	function handleClose(event: React.SyntheticEvent<any> | Event, reason: SnackbarCloseReason) {
		if(reason === "clickaway") return;
		setOpen(false);
	}
	
	return (
		<SnackbarContext.Provider value={displaySnackbar}>
			<Snackbar
				anchorOrigin={{
					vertical: "bottom",
					horizontal: "left",
				}}
				open={open}
				autoHideDuration={6000}
				onClose={handleClose}
				message={data?.message}
				action={data?.action} />
			{props.children}
		</SnackbarContext.Provider>
	);
}
Example #4
Source File: toast.tsx    From NekoMaid with MIT License 6 votes vote down vote up
Snackbars: React.FC = () => {
  const [, updateF] = useState<number>(0)
  useEffect(() => {
    update = updateF
    return () => { update = undefined as any }
  })

  return <Box sx={{
    position: 'fixed',
    top: 12,
    right: 44,
    zIndex: theme => theme.zIndex.modal + 1,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'flex-end',
    pointerEvents: 'none'
  }}><Toolbar sx={{ padding: '0!important' }} />{Object.values(toasts).map(it => React.createElement(Snackbar, it))}</Box>
}
Example #5
Source File: Snackbar.tsx    From frontend with MIT License 6 votes vote down vote up
function SnackBar() {
  const { getAlerts } = AlertStore

  const handleSnackBarClose = (
    _event: React.SyntheticEvent | Event,
    reason: SnackbarCloseReason,
  ) => {
    if (reason === 'clickaway') {
      return
    }
    AlertStore.hide()
  }
  const handleClose = () => AlertStore.hide()

  return (
    <>
      {getAlerts.map(({ id, show, duration, type, message }) => {
        return (
          <Snackbar
            key={id}
            open={show}
            anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            autoHideDuration={duration}
            onClose={handleSnackBarClose}>
            <Alert severity={type} onClose={handleClose}>
              {message}
            </Alert>
          </Snackbar>
        )
      })}
    </>
  )
}
Example #6
Source File: SnackbarContext.tsx    From firecms with MIT License 5 votes vote down vote up
SnackbarProvider: React.FC<PropsWithChildren<{}>> = ({ children }: PropsWithChildren<{}>) => {

    const [isOpen, setIsOpen] = useState(false);
    const [title, setTitle] = useState<string | undefined>(undefined);
    const [message, setMessage] = useState<string | undefined>(undefined);
    const [type, setType] = useState<SnackbarMessageType | undefined>(undefined);

    const close = () => {
        setIsOpen(false);
        setTitle(undefined);
        setMessage(undefined);
        setType(undefined);
    };

    const open = (props: {
        type: SnackbarMessageType;
        title?: string;
        message: string;
    }) => {
        const { type, message, title } = props;
        setType(type);
        setMessage(message);
        setTitle(title);
        setIsOpen(true);
    };

    return (
        <SnackbarContext.Provider
            value={{
                isOpen,
                close,
                open
            }}
        >

            {children}

            <Snackbar open={isOpen}
                      autoHideDuration={3000}
                      onClose={(_) => close()}>
                <Alert elevation={1}
                       variant="filled"
                       onClose={(_) => close()}
                       severity={type}>

                    {title && <div>{title}</div>}
                    {message && <div>{message}</div>}

                </Alert>
            </Snackbar>

        </SnackbarContext.Provider>
    );
}
Example #7
Source File: CodeBlock.tsx    From fluttertemplates.dev with MIT License 4 votes vote down vote up
function CodeBlock(params: CodeBlockParams) {
  const [code, setCode] = useState("");
  const isDarkTheme = useTheme().palette.mode === "dark";

  const [open, setOpen] = React.useState(false);

  const handleClose = (
    event: React.SyntheticEvent | Event,
    reason?: string
  ) => {
    if (reason === "clickaway") {
      return;
    }

    setOpen(false);
  };

  useEffect(() => {
    fetch(params.url)
      .then((response) => response.text())
      .then((textString) => {
        setCode(textString);
      });
  }, [params.url]);

  const _snackBarAction = (
    <React.Fragment>
      <IconButton
        size="small"
        aria-label="close"
        color="inherit"
        onClick={handleClose}
      >
        <Close fontSize="small" />
      </IconButton>
    </React.Fragment>
  );

  return (
    <div>
      <div
        style={{
          position: "relative",
        }}
      >
        <SyntaxHighlighter
          language="dart"
          style={!isDarkTheme ? github : dracula}
          showLineNumbers={false}
          customStyle={{
            maxHeight: `${params.height}`,
            fontSize: "0.95rem",
          }}
        >
          {code}
        </SyntaxHighlighter>

        <Button
          aria-label="Copy"
          size="medium"
          variant="contained"
          color="secondary"
          disableElevation
          style={{
            position: "absolute",
            top: "16px",
            right: "20px",
            borderRadius: "10rem",
          }}
          startIcon={<FileCopyRounded />}
          onClick={() => {
            copy(code);
            setOpen(true);
          }}
        >
          Copy
        </Button>
      </div>

      {!code && (
        <Grid
          container
          direction="column"
          justifyContent="center"
          alignItems="center"
          style={{
            minHeight: "40vh",
          }}
        >
          <Grid item>
            <CircularProgress size="1.5rem" thickness={8} color="secondary" />
          </Grid>
        </Grid>
      )}

      <Snackbar
        open={open}
        autoHideDuration={4000}
        onClose={handleClose}
        message="Code copied successfully!"
        action={_snackBarAction}
        TransitionComponent={SlideTransition}
      />
    </div>
  );
}
Example #8
Source File: DomLoader.tsx    From mui-toolpad with MIT License 4 votes vote down vote up
export default function DomProvider({ appId, children }: DomContextProps) {
  const [state, dispatch] = React.useReducer(domLoaderReducer, {
    loading: false,
    saving: false,
    unsavedChanges: 0,
    error: null,
    dom: null,
  });
  const api = React.useMemo(() => createDomApi(dispatch), []);

  React.useEffect(() => {
    let canceled = false;

    dispatch({ type: 'DOM_LOADING' });
    client.query
      .loadDom(appId)
      .then((dom) => {
        if (!canceled) {
          dispatch({ type: 'DOM_LOADED', dom });
        }
      })
      .catch((err) => {
        if (!canceled) {
          dispatch({ type: 'DOM_LOADING_ERROR', error: err.message });
        }
      });

    return () => {
      canceled = true;
    };
  }, [appId]);

  const lastSavedDom = React.useRef<appDom.AppDom | null>(null);
  const handleSave = React.useCallback(() => {
    if (!state.dom || lastSavedDom.current === state.dom) {
      return;
    }

    lastSavedDom.current = state.dom;
    dispatch({ type: 'DOM_SAVING' });

    client.mutation
      .saveDom(appId, state.dom)
      .then(() => {
        dispatch({ type: 'DOM_SAVED' });
      })
      .catch((err) => {
        dispatch({ type: 'DOM_LOADING_ERROR', error: err.message });
      });
  }, [appId, state.dom]);

  const debouncedhandleSave = useDebouncedHandler(handleSave, 1000);

  React.useEffect(() => {
    debouncedhandleSave();
  }, [state.dom, debouncedhandleSave]);

  React.useEffect(() => {
    if (state.unsavedChanges <= 0) {
      return () => {};
    }

    const onBeforeUnload = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      event.returnValue = `You have ${state.unsavedChanges} unsaved change(s), are you sure you want to navigate away?`;
    };

    window.addEventListener('beforeunload', onBeforeUnload);
    return () => window.removeEventListener('beforeunload', onBeforeUnload);
  }, [state.unsavedChanges]);

  useShortcut({ code: 'KeyS', metaKey: true }, handleSave);

  return (
    <DomLoaderContext.Provider value={state}>
      <DomApiContext.Provider value={api}>{children}</DomApiContext.Provider>
      <Snackbar open={!!state.error}>
        <Alert severity="error" sx={{ width: '100%' }}>
          Failed to save: {state.error}
        </Alert>
      </Snackbar>
    </DomLoaderContext.Provider>
  );
}