javascripthtmlcssreactjsreactcsstransitiongroup

React, transition group - css transitions when swapping components


I have a component that swaps child components in ( it is a small quiz, and the child components are questions. I am trying to animate the swap of components using ReactCSSTransitionGroup.

So, I have a function that renders the components, that I am swapping wrapping in the ReactCSSTransitionGroup like so :

render() {
  return (
    <div className=" questions-container">
      <ReactCSSTransitionGroup transitionName="switch">
        {this.renderQuiz(step)}
      </ReactCSSTransitionGroup>
    </div>
  );
}

The renderQuiz function is just a switch statement that returns the correct component based on the right state - something like this:

renderQuiz(step) {
  switch (step) {
    case 0:
      return (
        <StepZero />
      );
    case 1:
      return (
        <StepOne />
      );
    ....
  }
}

Step is just a local component variable (this.state.step). I see this only partially working - when the first component loads I see it fade in, but there is no transition between switching the components.

Here is the CSS associated with the transition:

.switch-enter {
  opacity: 0.01;
}

.switch-enter.switch-enter-active {
  opacity: 1.0;
  transition: opacity 500ms ease-in;
}

.switch-leave {
  opacity: 1.0;
}

.switch-leave.switch-leave-active {
  opacity: 0;
  transition: opacity 500ms ease-out;
}

Unsure how to get this to work properly. Any input would be greatly appreciated. Thanks!


Solution

  • I think this is due to missing transitionEnterTimeout and transitionLeaveTimeout as they determine how long the *-active classes remain applied.

    I think they default to zero, which would visually mean no transition since your transition CSS is on the -active class.

    render() {
        return (
            <div className=" questions-container">
               <ReactCSSTransitionGroup 
                   transitionName="switch"
                   transitionEnterTimeout={500}
                   transitionLeaveTimeout={500}
               >
                  {this.renderQuiz(step)}
              </ReactCSSTransitionGroup>
            </div>
        );
    }