Notistack: Ability to close snackbars on click away

Created on 10 Oct 2019  Â·  6Comments  Â·  Source: iamhosseindhv/notistack

I would love to have a property I can pass to SnackbarProvider and enqueSnackbar that would add a click away listener to the snackbar so it would auto dismiss upon the next user interaction

All 6 comments

notistack doesn't close snackbars on clickaway. but that doesn't mean you can't close snackbars on clickaway. You can do the following once v0.9.4 is released.

 <SnackbarProvider
    ref={(ele) => { this.ref = ele; }}
    onClose={(event, reason, key) => {
        if (reason === 'clickaway') {
            this.ref.closeSnackbar(key);
        }
    // ...
}}
 <SnackbarProvider
    ref={(ele) => { this.ref = ele; }}
    onClose={(event, reason, key) => {
        if (reason === 'clickaway') {
            this.ref.closeSnackbar(key);
        }
    // ...
}}

Inside the onClose method is it possible get the access to the snackbar properties? For example to avoid the clickaway handler if the snackbar is persistent.

No but you can store the key of your persistent snackbar somewhere and decide if you want to close it or not by comparing the keys. An easier approach would be to pass your own key in enqueueSnackbar options.

key: ‘persistent-someuniqueid’

And in onClose check if key startsWith persistent.

This way you don’t have to bother storing keys of persistent snackbars.

Thank you! I've chosen the second approach.

Thanks for the help!

Since we have access to the currently open snacks, we can just see if the one we are trying to close has persist set to true.

Here is an example in typescript.

      onClose={(event, reason, key): void => {
        if (reason === 'clickaway') {
          if (!ref.current) {
            return;
          }
          const currentSnack = ref.current.state.snacks.filter(snack => snack.key === key);
          if (currentSnack?.[0] && !currentSnack[0].persist) {
            ref.current.closeSnackbar(key);
          }
        }
      }}
      ref={ref}

Hi, here is a working example for those using react functional components:

import {SnackbarProvider} from 'notistack'

const notistackRef = React.createRef()

const AlertProvider = ({children}) => (
  <SnackbarProvider
    ref={notistackRef}

    onClose={(event, reason, key) => {
      if (reason === 'clickaway') {
        notistackRef.current.closeSnackbar(key)
      }
    }}
  >
    {children}
  </SnackbarProvider>
)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kubalobo picture kubalobo  Â·  5Comments

khanhdinovative picture khanhdinovative  Â·  3Comments

FabianoLothor picture FabianoLothor  Â·  4Comments

alexisab picture alexisab  Â·  5Comments

lsansaa picture lsansaa  Â·  7Comments