Mon, Apr 13, 2015
This is an example of creating a reusable modal component with React that supports CSS animations. You can find the source code here.
It would be fairly easy to create a specific modal component that is mounted and unmounted by toggling a bit of state in the parent component. However, what we want is a little more complex:
August 2018: Please note that this post was written for an older version of React. Changes in the code might be necessary to adapt it to the latest versions and best practices.
First, we bring in React's CSS Transition Group component:
Next, we create the modal. This component automates the following:
Note how we use this.props.children
to extract the component's body.
Rather than null
when the modal is not open, we return an empty transition group. We need to do this to keep the transition group component isolated inside the modal, so the parent of the modal doesn't have to instantiate it manually.
Now, for this example, we'll create an App
component to hold the state that tells React whether the modal is open, and a couple of methods to open and close it.
As you can see in render
, all we had to do was wrap the contents of the modal in the Modal
component, pass the state that determines whether its open, and give the CSS transition a name (We'll use this later). Inside the body, we make insert a call to the closeModal
method. There's no need to bind anything.
Finally, we render the App
component, and this concludes the JavaScript part of this example:
Most of the stylesheet is not important to this example, it's just giving the app and modal components a shape. The important part is the CSS animation classes that React will use.
The enter
selector sets the style for the component's initial state before animation begins, and enter-active
sets the final state:
leave
and leave-active
are the opposite:
© 2024. All rights reserved.