Scalable modals in React
Motivation
An easy way to show a modal when clicking on a button (or any other element). In a small project we can get away by repeating logic inside a class component but in a larger scale we need a reusable component that will make it a breeze to use modals.
The higher order component
We will use a higher order component (HOC) which will handle all the logic for toggling the modal:
There are a few things going on in the HOC above:
- We keep the state of the modal in the state using the
open
field. - The HOC will receive a
modalComponent
prop which will be the modal to be triggered. - The HOC will receive a
viewComponent
prop, which will be the component to be shown to the user to interact for the modal to open. - For the
viewComponent
we can either pass a function as children or an object (See examples below).
Modal implementation
Using the above HOC we can create a default implementation to be used by most of our modals in our application (Other implementations might include a confirmation modal, an alert modal e.t.c).
Note: We are using a modal component from semantic-ui-react but you could use any other modal (either a library or a custom one).
For this default implementation:
- We must pass a
viewComponent
prop which will be passed to the HOC as above. - We must pass a
header
prop which will be rendered as a header in our modal. - We must pass a
content
prop which will be rendered as the content of our modal.
Note: For the content we can either pass an object or a function, which will receive the toggleModal
prop.
Examples
Now we’ve done all the legwork for having a reusable modal component. See the examples below to see how easy it is to use a modal now:
Example 1
Here the viewComponent is an object. This is perfectly fine because our HOC will wrap that inside a div and give it the onClick callback to toggle the modal. The content also is an object is handled by the objectOrFunction
helper in the implementation above.
Example 2
Note: The form is incomplete in the above state.
This is an example to show a form inside a modal. Here we are taking control of the toggleModal prop as we are passing functions for both viewComponent
and content
. A potential complete solution would be to send an api request once the form is submitted and on a success toggle the modal.
Conclusion
The goal was to create a reusable and easy to use Modal component, which we achieved with the above code. Now showing something inside a modal is as easy as showing it anywhere in the page.