REACT Transition Group

React Transition Group is a powerful library for handling animations and transitions in React. It provides components to add animations when elements are added, removed, or updated in the DOM. This is particularly useful for managing dynamic content like modals, lists, and tooltips.

Installing React Transition Group

To get started, install the library:

npm install react-transition-group

Core Components of React Transition Group

  1. CSSTransition: Adds and removes CSS classes for animations.
  2. Transition: Manages low-level transition states.
  3. TransitionGroup: Handles animations for lists or groups of components.

1. CSSTransition Example

The CSSTransition component allows you to apply CSS classes during the lifecycle of an element.

Example: Fading In/Out a Component

npm install react-transition-group
/* App.css */
.fade-enter {
  opacity: 0;
}
.fade-enter-active {
  opacity: 1;
  transition: opacity 500ms;
}
.fade-exit {
  opacity: 1;
}
.fade-exit-active {
  opacity: 0;
  transition: opacity 500ms;
}
import React, { useState } from 'react';
import { CSSTransition } from 'react-transition-group';
import './App.css';

const App = () => {
  const [show, setShow] = useState(false);

  return (
    <div>
      <button onClick={() => setShow(!show)}>
        {show ? 'Hide' : 'Show'} Text
      </button>
      <CSSTransition
        in={show}
        timeout={500}
        classNames="fade"
        unmountOnExit
      >
        <p>This is an animated text!</p>
      </CSSTransition>
    </div>
  );
};

export default App;

2. TransitionGroup Example

The TransitionGroup component is ideal for animating lists or groups of elements. It works alongside CSSTransition.

Example: Animating a List of Items

/* App.css */
.item-enter {
  opacity: 0;
  transform: translateY(-20px);
}
.item-enter-active {
  opacity: 1;
  transform: translateY(0);
  transition: all 300ms;
}
.item-exit {
  opacity: 1;
  transform: translateY(0);
}
.item-exit-active {
  opacity: 0;
  transform: translateY(-20px);
  transition: all 300ms;
}
import React, { useState } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import './App.css';

const App = () => {
  const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);

  const addItem = () => {
    setItems([...items, `Item ${items.length + 1}`]);
  };

  const removeItem = (index) => {
    setItems(items.filter((_, i) => i !== index));
  };

  return (
    <div>
      <button onClick={addItem}>Add Item</button>
      <TransitionGroup>
        {items.map((item, index) => (
          <CSSTransition
            key={item}
            timeout={300}
            classNames="item"
          >
            <div>
              {item}
              <button onClick={() => removeItem(index)}>Remove</button>
            </div>
          </CSSTransition>
        ))}
      </TransitionGroup>
    </div>
  );
};

export default App;

3. Transition Example (Low-Level Control)

The Transition component provides granular control over animations by exposing states like entering, entered, exiting, and exited.

Example: Custom Animations

import React, { useState } from 'react';
import { Transition } from 'react-transition-group';

const duration = 500;

const defaultStyle = {
  transition: `opacity ${duration}ms ease-in-out`,
  opacity: 0,
};

const transitionStyles = {
  entering: { opacity: 1 },
  entered: { opacity: 1 },
  exiting: { opacity: 0 },
  exited: { opacity: 0 },
};

const App = () => {
  const [show, setShow] = useState(false);

  return (
    <div>
      <button onClick={() => setShow(!show)}>
        {show ? 'Hide' : 'Show'} Box
      </button>
      <Transition in={show} timeout={duration}>
        {(state) => (
          <div
            style={{
              ...defaultStyle,
              ...transitionStyles[state],
            }}
          >
            I'm a transition box!
          </div>
        )}
      </Transition>
    </div>
  );
};

export default App;

Features of React Transition Group

  • Uncomplicated Integration: Works seamlessly with CSS animations.
  • Control Over Animation State: Use lifecycle hooks like onEnter and onExited.
  • Dynamic Content Support: Animate components dynamically added to or removed from the DOM.

Best Practices

  1. Use CSS for Simplicity: Define animations in a .css file and manage state in React.
  2. Handle Unmounting: Use unmountOnExit to remove components from the DOM when they’re not visible.
  3. Combine with Libraries: For advanced animations, you can use libraries like Framer Motion alongside React Transition Group.