A Notification System with MobX and ReactJS
I want to find a consistent way to show notifications across all the pages and hopefully across all the screens.
I am sharing with you because:
- Often a personal suited solution it is not hard to accomplish without adding external libraries and dependencies
- The way I use ReactJS context feature is arguable… And I would love to read your points against it
I have considered toastr… it does what I need, but I can’t use it:
- it changes DOM directly
- it has JQuery as a dependency… and I care about bundle size
I have then searched for ReactJS libraries and I have found react-notification-system.
The demo is nice and it is tested, but I didn’t like the API…
I have in mind to define a MobX store for managing the notifications array and to access it everywhere in the app.
Here it is my very simple store:
What it feels wrong to me is mapping the store to properties and passing them along the DOM structure, because (for example) a very nested button could need access to a dispatcher event.
It feels right to me to put the global store inside the context and to access it directly in each component that I am not going to re-use for a different purpose. I have opened a discussion on the Mobx repo, trying to share my thoughts.
For example a custom <Button> component is too generic to access the context, but the <form> which contains it, it has a single purpose and it can get the store from the context and pass it through props to the button.
The notifications’ container is a flexbox styled with BassCSS class names and the notifications’ boxes are animated through React CSS transition Group.
With a little more effort I could use scoped class names even for the transition, but for the moment I don’t care about using global ones:
All my stores’ classes are instantiated in one single file, the same big singleton that I put in ReactJS context and the notification store is passed in the constructor of the stores that need it.
What do you think of this solution?