I have tried many ways for setting up a scalable way to create modals with React and Redux. The approach that I ended up using is basically a tweaked version from a Stackoverflow answer from Dan Abramov’s
Creating modals in React is pretty simple, many solutions implement React Portals but I think rendering a Modal outside of the application container is overkill, we use a ModalRoot container which we render in our application container instead.
So I talk here about a solution that is scalable, testable and simple. It requires some boilerplate code to setup but it’s worth it in the long run.
Here is a repository with the solution, keep reading if you want a detailed explanation.
First we setup a very basic Modal component, which we are going to use to implement different kinds of Modals such as Notification, Confirmation etc.
To keep things as simple as possible, I don’t use any css files, but I use styled-components. It’s a very nice library to add styling to your components, and I highly recommend you check it out, but feel free to translate the components styling to your project (scss, less etc.)
To create all the Redux logic and set this up correctly we are going to add/change:
First we have to add 2 new action types SHOW_MODAL and HIDE_MODAL to your project.
Next we are going to add 2 new action dispatchers showModal and hideModal
Now lets create a reducer to handle our actions.
NOTE: Don’t forget to include the reducer to your root reducer!
Next is creating a new file in your constants ModalTypes, more info on this later.
As you can see above, in the ModalTypes file we added Notification and Confirmation as modal types, lets first create a Notification modal.
The notification modal type is just to show a popup message with a button to close it (ok).
Another modal type we are going to add is a confirmation, which is slightly different than our notification modal type, because it asks the user to confirm (yes / no).
The ModalRoot container which we are going to create is responsible for rendering the correct modal component in your RootContainer with its correct properties.
The final step is to add your ModalRoot container to your RootContainer, depending on your project, this is mostly called App or Root.
So add the ModalRoot to your App container, in our example repository it looks like this:
So now everything is setup, but how do you use it? It’s pretty simple. Lets create an demo LoginView where we show 2 buttons:
What we have to do is pretty simple:
Lets look at the example situation (which I also used in the example repository)
So now you have a working and scalable implementation on how to use modals in your React, Redux application.
Another great reason why this solution is so great: you can now easily show a modal with different props everywhere, so if you want to show your designer a modal you have been working on: you simply call the action with its modal type + props and just like that it’s there.