[React] Modal with Backdrop and slide animation effects

Let’s assume there is a user story with the following requirements:

  • An overlay modal
  • A backdrop that can close the modal by clicking anywhere outside the modal area
  • Sliding up & down animation effects when opening and closing the modal

Setup

Install a dependency for animation:

$ npm install react-transition-group --save

Add two divs with id backdrop-root and overlay-root are added to index.html. These will be used to create portals.

Implementation

First of all, create Backdrop component. Notice this component has a click event handler in order to close the modal when user clicks outside the modal area.

Then, create ModalPortal component to create portals.

Here is the modal content. Let’s show a header and a button for closing the modal. Notice that CSSTransition from react-transition-group is applied for some animation effects. For this to work properly, we will need to define a couple of classes (modal-enter-active & modal-exit-active) in CSS. Refer to this page for more information regarding CSSTransition.

Also, I added a state to verify that the state gets cleared up when closing the modal and then gets set back to the initial value when the modal is opened again.

Here is our main component.

Lastly, applying some styles

Demo:

--

--

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