· 2 min read

migrate react-transition-group

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

Upgrading from react-transition-group v1 to v4 involves several key changes:

  1. The CSSTransitionGroup component has been removed.
  2. leave has been renamed to exit.
  3. transitionName has changed to classNames.
  4. Properties like transitionEnterTimeout have been consolidated into a timeout object.
  5. transition{Appear, Enter, Leave} have been simplified to appear, enter, and exit.

If your component uses any of the following lifecycle methods, it’s a bit more complicated as you’ll need to remove them manually:

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

If there are no peculiar hacks involved, you might consider using jscodeshift for the migration. If your component has become too complex to migrate easily, you can create a wrapper that encapsulates the original props:

/**
 * NOTE:
 * This is a 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 approach allows for a smooth transition. However, for ease of maintenance, it’s still advisable to gradually phase out these legacy features.

Related Posts

Explore Other Topics