Simple Custom Alerts In A React Application

I have a very simple way of creating and showing alerts in my React applications. I simply fix an alert container component to the top-right of my application, and this component renders an alert component for each object in the global redux state's alerts property. An alert object in the state.alerts array has three properties: an id, some text, and a style. The id can be used to dispatch an action to dismiss the alert and style is just an additional class name for the alert component.

Showing an alert is as simple as dispatching an action. I have a git repository/npm package that contains the code I normally use, along with an example application. Here, I'm going to go through the code and explain how to use/recreate it.

Reducer

The reducer is set up as follows. The alerts reducer is just an array of alert objects, which actions add and remove.

Component

Here's the AlertsOverlayComponent, which is the container that displays our alerts. In my source code this component isn't connected to redux, so that we have the option to pass in the alerts as a prop directly.

Usage

This is code from the example/ directory of my react-alerts-overlay-component. Here, Main is a component that's connected to redux, and it passes alerts to AlertsOverlayComponent as a prop. In most cases it would make more sense to directly connect AlertsOverlayComponet to redux using the same mapAlertsToProps that we see here.