๐Ÿ“ฝ๏ธ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

components/Backdrop.module.css
.backdrop {
  position: fixed;
  z-index: 100;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.65);
}

.backdropOpen {
  display: block;
}

.backdropClose {
  display: none;
}

Using the components

App.js
import {useState} from 'react';
import Backdrop from './components/Backdrop';
import Modal from './components/Modal';

const App = () => {
  const [showModal, setShowModal] = useState(false);
  
  const showModalHandler = () => {
    setShowModal(true);
  }
  const hideModalHandler = () => {
    setShowModal(false);
  }
  return (
    <>
      <h1>React Animations</h1>
      <Backdrop show={showModal} close={closeModalHandler} />
      <Modal show={showModal} close={closeModalHandler} />
      <button onClick={showModalHandler}>Show Modal</button>
    </>
  );
}

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 animation keyframes will not be able to run on that component.

const App = () => {
 //...
 //...
 return (
  {showModal && <Backdrop show={showModal} close={closeModalHandler} />}
  {showModal && <Modal show={showModal} close={closeModalhandler}/>}
 );
}

We overcome these issues using a third party library called react-transition-group.

Last updated