[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
Install a dependency for animation:
$ npm install react-transition-group --save
Add two divs with id
overlay-root are added to
index.html. These will be used to create portals.
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.
ModalPortal component to create portals.
Here is the modal content. Let’s show a header and a button for closing the modal. Notice that
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
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