react-router icon indicating copy to clipboard operation
react-router copied to clipboard

Animation Switch not compatible with react-transition-group v2

Open Noitidart opened this issue 9 years ago • 27 comments

This is regarding - https://github.com/ReactTraining/react-router/issues/4351

So react-transition-group is superceeding react-addons-css-tranistion-group - https://github.com/reactjs/react-transition-group

Transition API v2 expects immediate children of <TransitionGroup> to be <CSSTransition>.

React Router <Switch> expects immediate children to be of type <Route>.

Does this mean it is not possible to do this with v2 transition api? I put some details/code here - https://github.com/reactjs/react-transition-group/issues/83

Noitidart avatar Jun 25 '17 00:06 Noitidart

This is simple usage of v2 transition api:

import React, { Component } from 'react'
import { render } from 'react-dom'
import { TransitionGroup, CSSTransition } from 'react-transition-group'

import './index.css'

class App extends Component {
    state = {
        theme: 1
    }
    upTheme = () => this.setState(({ theme }) => ({ theme:theme+1 }));
    render() {
        const { theme } = this.state;
        return (
            <TransitionGroup className="rawr">
                <CSSTransition appear timeout={{appear:1000,enter:2000,exit:1000}} classNames="pagefade" key={theme.toString()}>
                    <span className="mydiv" onClick={this.upTheme}>{theme}</span>
                </CSSTransition>
            </TransitionGroup>
        );
    }
}

CSS:

.pagefade-enter, .pagefade-appear { opacity:0; }
.pagefade-enter.pagefade-enter-active,
.pagefade-appear.pagefade-appear-active { opacity:1; transition:opacity 1000ms; }
.pagefade-enter.pagefade-enter-active { transition-delay:1000ms; }
.pagefade-exit { opacity:1; }
.pagefade-exit.pagefade-exit-active { opacity:0; transition:opacity 1000ms; }

Noitidart avatar Jun 25 '17 01:06 Noitidart

https://hackernoon.com/animated-page-transitions-with-react-router-4-reacttransitiongroup-and-animated-1ca17bd97a1a

timdorr avatar Jun 26 '17 02:06 timdorr

Thanks @timdorr for the fast reply when you are so busy. However this article is not related to react-transition-group v2 - it is very different. Please don't mind the thumbs down, I just don't want others going there and wasting their time.

Noitidart avatar Jun 26 '17 03:06 Noitidart

You need to make sure you're assigning key props to everything. That's the trick.

timdorr avatar Jun 26 '17 03:06 timdorr

Not sure whether this is what you want, but here is how I use react-transition-group v2 with react-router v4:

<TransitionGroup>
    <CSSTransition key={this.props.location.key} timeout={500} classNames="fading-animation-transition" mountOnEnter={true} unmountOnExit={true}>
        <Switch location={this.props.location}>
            <Route path="/" exact component={Home} />
            <Route path="/blog" component={Blog} />
            <Route path="/albumn" component={Albumn} />
        </Switch>
    </CSSTransition>
</TransitionGroup>

horizon-blue avatar Jul 09 '17 06:07 horizon-blue

Thank you so so much @Horizon-Blue !! That is exactly what I was trying to do. Thanks so much!

Noitidart avatar Jul 09 '17 06:07 Noitidart

Thank you it works well !

There is still the case when you have sub routes, the transition will be triggered on every sub routes changes.

hlehmann avatar Jul 09 '17 09:07 hlehmann

@hlehmann Yeah, that's because location.key keeps changing every time the route gets an update. To solve this problem, you can try using this.props.location.pathname instead of this.props.location.key, and using split() to get the prefix. e.g.

<TransitionGroup>
    <CSSTransition key={this.props.location.pathname.split('/')[1]} timeout={500} classNames="fading-animation-transition" mountOnEnter={true} unmountOnExit={true}>
        <Switch location={this.props.location}>
            <Route path="/" exact component={Home} />
            <Route path="/blog" component={Blog} />
            <Route path="/albumn" component={Albumn} />
        </Switch>
    </CSSTransition>
</TransitionGroup>

This will trigger the animation if I switch from /blog to /albumn, but will not trigger if I switch from /blog to /blog/post

horizon-blue avatar Jul 09 '17 10:07 horizon-blue

Yes that's the solution I came out. But maybe a more integrated solution like a could avoid this trick.

hlehmann avatar Jul 09 '17 18:07 hlehmann

@Horizon-Blue It works, but trow this error. Don't know what's wrong.

removeClass.js:4 Uncaught TypeError: Cannot read property 'classList' of null
    at removeClass (removeClass.js:4)
    at CSSTransition.removeClasses (CSSTransition.js:267)
    at Object.CSSTransition._this.onExit (CSSTransition.js:228)
    at Transition.performExit (Transition.js:250)
    at Transition.updateStatus (Transition.js:195)
    at Transition.componentDidUpdate (Transition.js:159)
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at eval (ReactCompositeComponent.js:729)
    at CallbackQueue.notifyAll (CallbackQueue.js:76)
    at ReactReconcileTransaction.close (ReactReconcileTransaction.js:80)
    at ReactReconcileTransaction.closeAll (Transaction.js:206)
    at ReactReconcileTransaction.perform (Transaction.js:153)
    at ReactUpdatesFlushTransaction.perform (Transaction.js:140)
    at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)
    at Object.flushBatchedUpdates (ReactUpdates.js:172)
    at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)
    at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)
    at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
    at Object.batchedUpdates (ReactUpdates.js:97)
    at dispatchEvent (ReactEventListener.js:147)

followdarko avatar Jul 17 '17 00:07 followdarko

@DGizmo Seems like the problem is that ReactDOM.findDOMNode(this) returns null when your component switch to exit state.

As in facebook/react#4651, ReactDOM.findDOMNode will return null when the component is unmounted or the ref changes. Are you unmounting or re-referencing the DOM node inside your route?

I don't know enough about your setup to give a suggestion, but in my personal experience, I always found it very helpful to wrap everything inside CSSTransition with a div. This will not only ensure that CSSTransition always have a DOM node to work on (so findDOMNode won't return null), but also allow me to separate route transition and all the other animation within the route (otherwise, the animation will be applied to the outermost DOM node inside your route, which might not be what you want)

So here is how you can wrap your routes, notice the div with class WRAPPER:

 <TransitionGroup>
    <CSSTransition key={this.props.location.pathname.split('/')[1]} timeout={500} classNames="fadeTranslate" mountOnEnter={true} unmountOnExit={true}>
        <div className="WRAPPER">
            <Switch location={this.props.location}>
                <Route path="/" exact component={Home} />
                <Route path="/blog" component={Blog} />
                <Route path="/albumn" component={Albumn} />
            </Switch>
        </div>
    </CSSTransition>
</TransitionGroup>

And the classNames you give CSSTransition will be applied to this div:

image

Give it a try :). Let me know if the issue still persists.

horizon-blue avatar Jul 17 '17 01:07 horizon-blue

Now it works without errors, thank you @Horizon-Blue! But because of the additional wrapper layer I had to rework my animations. Well, now it looks complex :)

followdarko avatar Jul 17 '17 11:07 followdarko

Thank you very much @Horizon-Blue for your help on this. The article linked on hackernoon in the comment above - https://github.com/ReactTraining/react-router/issues/5279#issuecomment-310946205 - is not useful for react-transition-group v2 - so I really appreciate you giving this help.

Noitidart avatar Jul 17 '17 18:07 Noitidart

This was very helpful @Horizon-Blue. Any thoughts on how one might achieve different transitions for each route?

andrewcroce avatar Jul 19 '17 13:07 andrewcroce

@andrewcroce I can't think of any elegant way to approach this... though one thing you can try is to define a custom map from pathname to corresponding css transition effect, e.g.:

const transitionMap = {
    blog: { classNames: 'fade-translate', timeout: 500 },
    albumn: { classNames: 'fade-in-out', timeout: 300 },
    account: { classNames: 'fade-translate', timeout: 550 },
};

and in your route definition:

render = () => {
    const current = this.props.location.pathname.split('/')[1];
    return (
        <TransitionGroup>
            <CSSTransition
                key={current}
                classNames="default-transition"
                timeout={300}
                {...transitionMap[current]}
                mountOnEnter={true}
                unmountOnExit={true}
            >
                <div>
                    <Switch location={this.props.location}>
                        <Route path="/blog" component={Blog} />
                        <Route path="/albumn" component={Albumn} />
                        <Route path="/about" component={About} />
                        <Route path="/account" component={Account} />
                    </Switch>
                </div>
            </CSSTransition>
        </TransitionGroup>
    );
};

If there is no special transition defined for a route, then default-transition will be used. Otherwiese, {...transitionMap[current]} will override previously defined transitions.

This might not be the best way to solve the problem, but it should work... :P

horizon-blue avatar Jul 21 '17 01:07 horizon-blue

Thanks so much @Horizon-Blue to help us brainstorm these ideas. I also have a need in the future for varied transitions per route, I will share my brainstorm here when I get to work on that. :)

Noitidart avatar Jul 21 '17 07:07 Noitidart

Thanks @Horizon-Blue. This is a helpful idea.

andrewcroce avatar Jul 26 '17 01:07 andrewcroce

Here is a working fade page transition example with React Router v4 and React Transition Group v2: https://codesandbox.io/s/4RAqrkRkn?view=preview

Related issue on how it was created.

vladshcherbin avatar Jul 28 '17 03:07 vladshcherbin

Thanks for your help @Horizon-Blue .Now the page sliding animation is OK.

const RouterMap = () => (
  <Router>
    <Route render={({ location }) =>
      <TransitionGroup>
        <CSSTransition key={location.pathname.split('/')[1]} timeout={500} classNames="pageSlider" mountOnEnter={true} unmountOnExit={true}>
          <Switch location={location}>
            <Route path="/" exact component={ Index } />
            <Route path="/comments" component={ Comments } />
            <Route path="/opinions" component={ Opinions } />
            <Route path="/games" component={ Games } />
          </Switch>
        </CSSTransition>
      </TransitionGroup>
    } />
  </Router>
)

And the css:

.pageSlider-enter {
  transform: translate3d(100%, 0, 0);
}

.pageSlider-enter.pageSlider-enter-active {
  transform: translate3d(0, 0, 0);
  transition: all 600ms;
}
.pageSlider-exit {
  transform: translate3d(0, 0, 0);
}

.pageSlider-exit.pageSlider-exit-active {
  transform: translate3d(-100%, 0, 0);
  transition: all 600ms;
}

The animation is as bellow:

pageslidinganimation

As you see, the animation that index page slide to the detail page is all right. But when I click the Back icon, I hope 'index page' comes out from left to right.

I know if I change the CSS as bellow, the page will come out from left to right:

.pageSlider-enter {
  transform: translate3d(-100%, 0, 0);
}
.pageSlider-exit.pageSlider-exit-active {
  transform: translate3d(100%, 0, 0);
  transition: all 600ms;
}

But how combine the two animations together? Generally speaking, whenever user clicks the back icon, the animation should be from left to right. Do you have any idea? Many thanks.

jasonintju avatar Aug 29 '17 06:08 jasonintju

Hi @jasonintju , you could try something similar to the method discussed in https://github.com/ReactTraining/react-router/issues/5279#issuecomment-316877263 to specify a different class for the root page.

e.g.

const isRoot = location.pathname === '/';

and then

<CSSTransition key={location.pathname.split('/')[1]} timeout={500} classNames={isRoot ? 'left-to-right' : 'right-to-left'} mountOnEnter={true} unmountOnExit={true}>

horizon-blue avatar Aug 29 '17 16:08 horizon-blue