Timbo
Timbo

Reputation: 125

Transitions partially working in react router 4

I am trying to animate transitions between routes using react router 4 and CSSTransitionGroup. The appear to work partially - the entering component sometimes animates as desired (but not always), the exiting component disappears with no transition. Here is the render function that is not behaving as desired:

render() { 

    /****************************************For transitions***********/
    // const locationKey = this.props.location.pathname;

    return (
        <CSSTransitionGroup
          key={this.props.location.key}
          transitionName="flipIt"
          transitionAppear={true}
          transitionAppearTimeout={3000}
          transitionEnterTimeout={3000}
          transitionLeaveTimeout={3000}
        >
        <Switch key={this.props.location.pathname} location={this.props.location}>
            <Route exact path='/' component={Welcome} />
            <Route path='/game' render={(props) => (
              <Board {...props} leaders={this.state.leaders} logGameGoes={this.setGameGoes} />
            )} />
            <Route path='/leaderboard' render={(props) => (
              <Leaderboard {...props} leaders={this.state.leaders} syncLeaders={this.syncLeaders} />
            )} />
            <Route path='/winner' render={(props) => (
              <Winner {...props} addLeader={this.addLeader} />
            )} />
            <Route path='/gameover' render={(props) => (
              <Gameover {...props} goes={this.state.currentGameGoes} />
            )} />
          </Switch>
        </CSSTransitionGroup>
    );
  }
}

export default withRouter(App);

The whole app can be seen at this Sandbox: https://codesandbox.io/s/vyn7zl2993

Many thanks for any help.

Upvotes: 1

Views: 649

Answers (1)

Dennie de Lange
Dennie de Lange

Reputation: 2934

Switch will render a matched route. Lets say game is matched => game will render and the appear transition will run once the component is mounted. Now you go to winner, this will unmount game and mount the winner route. You'll be expecting the leave transition to start for game, but what will happen is that game will be removed from the dom (because of the unmount), so there's nothing to run and the leave transition will not work. The appear transition will start on the winner route. So what to do?

You can use a children func (https://reacttraining.com/react-router/web/api/Route/children-func) and make the component invisible before unmounting the route. You can't use Switch for this, because it renders routes exclusively.

Upvotes: 1

Related Questions