DEV Community

Sakibul Anwar
Sakibul Anwar

Posted on • Edited on

How to use Notistack snackbar outside of react components

Notistack is great tool for handling notifications. Sometimes we create a separate js file for calling api. But normally it is not available outside of react components.

Today we are gonna solve this issue.For this we have to follow couple of steps.

I'm showing this for NextJS

JavaScript



import { useSnackbar } from 'notistack';

let useSnackbarRef;
export const SnackbarUtilsConfigurator = () => {
  useSnackbarRef = useSnackbar();
  return null;
};

export default {
  success(msg) {
    this.toast(msg, 'success');
  },
  warning(msg) {
    this.toast(msg, 'warning');
  },
  info(msg) {
    this.toast(msg, 'info');
  },
  error(msg) {
    this.toast(msg, 'error');
  },
  toast(msg, variant = 'default') {
    useSnackbarRef.enqueueSnackbar(msg, { variant,    autoHideDuration: 1500 });
  },
};


Enter fullscreen mode Exit fullscreen mode

TypeScript



import { useSnackbar, VariantType, WithSnackbarProps } from 'notistack'

let useSnackbarRef: WithSnackbarProps
export const SnackbarUtilsConfigurator: React.FC = () => {
  useSnackbarRef = useSnackbar()
  return null
}

export default {
  success(msg: string) {
    this.toast(msg, 'success')
  },
  warning(msg: string) {
    this.toast(msg, 'warning')
  },
  info(msg: string) {
    this.toast(msg, 'info')
  },
  error(msg: string) {
    this.toast(msg, 'error')
  },
  toast(msg: string, variant: VariantType = 'default') {
    useSnackbarRef.enqueueSnackbar(msg, { variant })
  }
}


Enter fullscreen mode Exit fullscreen mode

Import SnackbarProvider from notistack
Import the SnackbarUtilsConfigurator function in _app.js.

Image description

Example
Image description

Thank you for reading

Connect With Me : Github LinkedIn

Top comments (1)

Collapse
 
ayush_singhal_1b663cd2aa3 profile image
Ayush Singhal

Hello @sakiblite, In this code above "WithSnackbarProps" is no more available in notistack, can you help me with this ?