Estimate Project

Creating reusable modal window in React\Alt

by | March 2nd, 2017

gera-reactIn this article, I would like to show you the way of creating a reusable modal window in React.

But why is it worth doing? Because it makes the code more clean and transparent, helps to follow DRY convention and avoid making code too complicated. To implement this I used React, alt, reactstrap – as UI kit. Let’s start with the store – ModalStore.js

We will use storage to store props of the modal window, like button names and types, title and content. ‘Visible’ property is responsible for the state of modal window(visible\hidden)

Next thing we need is action that keeps the store updated. It is how flux works. If you use redux – it’s called “reducer”

Component code:

The component has default functions and render(), which includes all UI that uses state from the ModalStore.jsx. The function componentDidMount() listening for the store changes and the react responds to it with re-render of that component. It goes automatically and we do not need to track the moment of the store updating, because of how react works.

Let’s see how we use modal window with other components. For example, we have a button that should open modal window.

As you may see from the code, we pass the object from the modalParams() to ModalAction, which contains our chosen properties. For each of the properties, we can use inline data, or component with its own logic, which can provide you 1 more abstraction layer for your logic.


Finally add modal component to your layout


This is a very simple way to customize your component for any required case without duplicating the code and at the same time to keep control over the modal window.

In this example, I used modal window from bootstrap 4, but it can be replaced with any other.


  Be Gera-Successful RB_4

Tags: , ,