What might cause an MUI Snackbar to not generate the correct class names?

Viewed 121

I'm trying to show a notification on my Gatsby blog when the service worker updates, using an MUI Snackbar toast. Sometimes the toast doesn't have any styling, and looks like this:

Snackbar without style

It should look like this:

Correct Snackbar toast

I can see that the <Snackbar> and MUIAlert don't output the correct classes on their divs.

The code is below:

export default function Layout({ children }: { children: ReactNode }): ReactElement {
  const [toastOpenState, setToastOpenState] = React.useState(isBrowser() && Boolean(localStorage.getItem('serviceWorkerUpdated')));

  function handleToastClose(): void {
    setToastOpenState(false);
  }

  return (
    <>
      <TopNav/>

      <Snackbar className="toast"
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        open={toastOpenState}
        onClose={handleToastClose}
        TransitionComponent={Transition}
      >
        <MuiAlert severity="success" variant="filled" elevation={6} onClose={handleToastClose}>
          A new version is available.
          <Button onClick={() => {
            localStorage.removeItem('serviceWorkerUpdated');
            window.location.reload();
          }}>Reload</Button>
        </MuiAlert>
      </Snackbar>

      <div style={{ flex: 1, margin: '0 1em' }}>
        {children}
      </div>
      <Footer />
    </>
  );
}
1 Answers

The solution was to move setting the open state of the toast to true from an onEffect hook:

  const [toastOpenState, setToastOpenState] = React.useState(false);
  useEffect(() => {
    if (localStorage.getItem('serviceWorkerUpdated'))
      setToastOpenState(true);
  }, []);

  // Called by clicking the close button
  function handleToastClose(): void {
    setToastOpenState(false);
  }

  return (
    <>
      ... same stuff
    </>
  );
}

Related