How to add animations with the react-transition-group library?

To add animations with the react-transition-group library, follow these steps:

  1. Install the react-transition-group library by running the following command in your terminal:
npm install react-transition-group
  1. Import the necessary components from the react-transition-group library in your React component file:
import { CSSTransition } from 'react-transition-group';
  1. Wrap the element you want to animate with the CSSTransition component and specify the CSS classes for the entering and exiting states:
<CSSTransition in={isShowing} timeout={200} classNames="fade" unmountOnExit > <div className="box">Content to animate</div> </CSSTransition>
  1. Define the CSS animations for the entering and exiting states in your CSS file:
.fade-enter { opacity: 0; } .fade-enter-active { opacity: 1; transition: opacity 200ms ease-in; } .fade-exit { opacity: 1; } .fade-exit-active { opacity: 0; transition: opacity 200ms ease-out; }
  1. Manage the state to trigger the animation by updating the isShowing state variable:
const [isShowing, setIsShowing] = useState(false); const handleClick = () => { setIsShowing(!isShowing); };
  1. Trigger the animation by changing the state:
<button onClick={handleClick}>Toggle Animation</button>

By following these steps, you can add animations to your React components using the react-transition-group library. You can explore other features of the library such as <TransitionGroup> for managing multiple elements with animations.