๐ฝ๏ธAnimations in React
Working with react-transition-group
Basics of Animation
In this section, we'll learn how to animate basic HTML elements [or JSX elements] in React.
Creating the components
Suppose we want to animate the showing and hiding of a modal. First, let's create the modal & backdrop components, and add the show & hide features to it. We'll be using CSS Modules here.
Adding styles
Using the components
Problems with basic animations
There are a few basic issues with the above approach:
The
Backdrop
&Modal
components are always rendered in the DOM, because we are not conditionally rendering them, and hence are always present, irrespective of whether we need them or not. We are showing and hiding the modal using CSS, not actually attaching and removing these components from the DOM, which should be the actual behavior.To conditionally render the Backdrop & Modal components, we can do that, but it will break the animation functionality. The problem here will arise when we close the modal. When we change the state of
showModal
to false, React will immediately remove the component from the DOM, and our animationkeyframes
will not be able to run on that component.
We overcome these issues using a third party library called react-transition-group
.
Last updated