· 2 min read

Migrating react-transition-group

This article was auto-translated from Chinese. Some nuances may be lost in translation.

Here are several key points to note when upgrading react-transition-group from v1 to v4:

  1. After the upgrade, the CSSTransitionGroup component was removed.
  2. leave became exit.
  3. transitionName became classNames.
  4. Props like transitionEnterTimeout were replaced by a timeout object.
  5. transition{Appear, Enter, Leave} became appear, enter, exit.

If your components use any of the following lifecycle methods, it will be a bit more troublesome, as you’ll have to remove them yourself:

  • componentWillAppear
  • componentDidAppear
  • componentWillEnter
  • componentDidEnter
  • componentWillLeave
  • componentDidLeave

If you don’t have any strange hacks, you can also consider using jscodeshift for the migration. If your components have grown too bloated to migrate easily, you can create a wrapper component to adapt the legacy props:

/**
 * NOTE:
 * This is temporary wrapper component for Transition.js,
 * It provides the same API as `CSSTransitionGroup` in v1
 */
import * as React from 'react';
import { TransitionGroup, CSSTransition } from 'react-transition-group';

type Props = {
  component?: React.ReactNode;
  transitionName: string;
  transitionEnterTimeout?: number;
  transitionExitTimeout?: number;
  transitionEnter?: boolean;
  transitionExit?: boolean;
  children: React.ReactNode,
};

const CSSTransitionGroup = ({
  transitionEnterTimeout= 0,
  transitionExitTimeout= 0,
  transitionEnter= true,
  transitionExit= true,
  transitionName,
  children,
  component,
}: Props) => {
  const transitionChildrenProps = {
    classNames: transitionName,
    timeout: { enter: transitionEnterTimeout, exit: transitionExitTimeout }
  };

  const transitions = React.Children.map(children, (child: any) => (
    <CSSTransition key={`transition-${child.key}`} {...transitionChildrenProps}>{child}</CSSTransition>
  ));

  return (
    <TransitionGroup
			component={component}
			enter={transitionEnter}
			exit={transitionExit}
 		>
      {transitions}
    </TransitionGroup>
  );
};

export default CSSTransitionGroup

This way, you can achieve a painless migration. However, for the sake of maintainability, it is still better to phase it out gradually.

Related Posts

Explore Other Topics