reactjsreact-transition-group

How to trigger React TransitionGroup and Transition to animate onLoad


Given the React component below which uses React Transition Group, how can I get the Transition animation to render on component load?

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

const FeatureItem3 = class extends React.Component {
  constructor() {
    super();
    this.state = {
      animate: true,
    };
  }
  render() {
    return (           
        <TransitionGroup>
          <Transition
            in={this.state.animate}
            timeout={0}
          >
            <div>xxx</div>
          </Transition>
          <Transition
            in={this.state.animate}
            timeout={1000}
          >
            <div>yyyy</div>
          </Transition>
          <Transition
            in={this.state.animate}
            timeout={2200}
          >
            <div>zzzz</div>
          </Transition>
        </TransitionGroup>
    );
  }
};

Solution

  • By default the Transition component does not alter the behavior of the component it renders, it only tracks "enter" and "exit" states for the components. It's up to you to give meaning and effect to those states.

    https://reactcommunity.org/react-transition-group/transition

    Example from their docs:

    import Transition from 'react-transition-group/Transition';
    
    const duration = 300;
    
    const defaultStyle = {
      transition: `opacity ${duration}ms ease-in-out`,
      opacity: 0,
    }
    
    const transitionStyles = {
      entering: { opacity: 0 },
      entered:  { opacity: 1 },
    };
    
    const Fade = ({ in: inProp }) => (
      <Transition in={inProp} timeout={duration}>
        {(state) => (
          <div style={{
            ...defaultStyle,
            ...transitionStyles[state]
          }}>
            I'm a fade Transition!
          </div>
        )}
      </Transition>
    );