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:

  1. The HOC will receive a modalComponent prop which will be the modal to be triggered.
  2. 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.
  3. 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).

  1. We must pass a header prop which will be rendered as a header in our modal.
  2. We must pass a content prop which will be rendered as the content of our modal.

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:

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.

Software developer, writer, speaker, photographer.

Software developer, writer, speaker, photographer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store