B
B
bormor2018-03-24 19:21:44
css
bormor, 2018-03-24 19:21:44

React - route change animation. How to set different animations based on URL?

I figured out how to add an animation to the appearance and disappearance of a component for the route.
And how can I add animation based on the URL? (More precisely, the nesting level)
How to google solutions to such a problem?
The goal is to make the animation of the route change like in the slider.
For example:
When going from /user1/ to /user1/tasks/ - "slide from right to left"
When going from /user1/tasks/ to /user/ - "slide from left to right"

Snippet of current code
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link, Switch, withRouter } from 'react-router-dom';
import { TransitionGroup, CSSTransition } from 'react-transition-group';

import './index.css'


const App = withRouter(({ location }) => (
  
    <div>

      <Link to="/">Home</Link> <br/>
      <Link to="/user1">User1</Link> <br/>
      <Link to="/user2/commit2">User2/commit2</Link>

      <hr />

      <TransitionGroup>
        <CSSTransition
          key={location.key}
          classNames='slide'
          timeout={1000}
        >
          <Switch>
            <Route exact path="/" component={HomePage} />
            <Route exact path="/:user" component={UserPage} />
            <Route path="/:user/:commit" component={CommitPage} />
          </Switch>
        </CSSTransition>
      </TransitionGroup>

    </div>
  
));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-03-25
@bormor

First of all, you need to understand how your route changes (there are more or less segments).
In order to calculate this, we need to compare the previous route with the current one when updating the component.
Option #1: Change SFC to a class and use componentWillReceiveProps. Accordingly, there you track how the route has changed and write to setState.
Option #2: memoization with some HOC, like this

const withPrevProps = (Component) => {
    let prevProps = null;
    return (props) => {
        const component = (
            <Component
                {...props}
                prevProps={prevProps}
            />
        );
        prevProps = props;
        return component;
    };
};

const App = withRouter(withPrevProps(({ location, prevProps }) => (
  ...
)));

In both cases, in the render, you expose the classes in accordance with how your route has changed.
<CSSTransition
    classNames={'slide-' + slideDirection}
 ...

I didn't do a live example, but it seems like it should work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question