First, you have to install the necessary dependencies for group transitions. You can do this by either:
1. Using npm:
`npm install react-transition-group`
or
1. Using yarn:
`yarn add react-transition-group`
Then, you can import the TransitionGroup and CSSTransition components into your React component file:
```
import { TransitionGroup, CSSTransition } from ‘react-transition-group’;
```
React Transition Group exports three components: TransitionGroup, CSSTransition, and Transition.
- TransitionGroup is a state machine for managing the mounting and unmounting of components over time.
- CSSTransition tie to classes in the CSS file.
- Transition is a simple transition component, that allows you to describe a transition from one component state to another over time with a simple declarative API.
Here is an example of how to use these components together:
```
import React from “react”;
import { TransitionGroup, CSSTransition } from “react-transition-group”;
function ExampleComponent({ items }) {
return (
}
```
In this example:
- TransitionGroup is a state machine for managing the mounting and unmounting of components over time.
- Items are rendered within the CSSTransition component. Each item needs a unique key prop and any items that are added or removed will automatically be animated.
- timeout is the number of milliseconds for the animation to complete.
- classNames is the name of the base CSS class. This should match up with the classes in your CSS files. In this case, we should have item-enter and item-exit defined in CSS. These classes will be applied at different stages of the animation.
For animations to work you also need to have the corresponding CSS classes defined:
```
.item-enter {
opacity: 0;
}
.item-enter-active {
opacity: 1;
transition: opacity 500ms;
}
.item-exit {
opacity: 1;
}
.item-exit-active {
opacity: 0;
transition: opacity 500ms;
}
```
These classes define what the enter and exit animations should look like. Here, we’re only changing the opacity, but you could also add transformations or other properties.
This is a simple example. Depending on the complexity of your animations, you may have to adjust this code to fit your needs. Always remember to provide keys when mapping over items so the TransitionGroup knows how to apply animations when items are added or removed.