javascriptreactjsnotificationsmaterial-uisnackbar

How to implement material-ui Snackbar as a global function?


I am creating my react app with material-ui Snackbar. In my project I have a lot of components and don't want to insert <Snackbar/> in each of them. Is there a way to create function that will show snackbar, then just import and use this function in each component?

Something like:

import showSnackbar from 'SnackbarUtils';

showSnackbar('Success message');


Solution

  • You have to do it in react way. You can achieve this by creating a Higher Order Component.

    1. Create a HOC that returns a snackbar component along with the wrappedComponent
    2. Create a function in that HOC which accepts message, severity (if you are using Alert like me), duration and sets the appropriate states which are set to the props of the snackbar. And pass that function as a prop to the wrappedComponent.
    3. Finally import this HOC wherever you want to display a snackbar, pass your component in it and call the HOC function from the prop (this.prop.functionName('Hello there!')) in the event handler where you want to display a snackbar and pass in a message.

    Check this out. https://stackblitz.com/edit/snackbar-hoc?file=src/SnackbarHOC.js