painless transitions built for react-router, powered by react-motion

Last update: May 8, 2022

React Router Transition

Painless transitions for React Router, powered by React Motion. Example site.

Requirements

To use the latest version of this package (2.x), you'll need to use a version of React compatible with hooks, as well as version 5.x of react-router-dom.

Installation

npm install --save react-router-transition react-router-dom

Example Usage

import { BrowserRouter as Router, Route } from 'react-router-dom';
import { AnimatedSwitch } from 'react-router-transition';

export default () => (
  <Router>
    <AnimatedSwitch
      atEnter={{ opacity: 0 }}
      atLeave={{ opacity: 0 }}
      atActive={{ opacity: 1 }}
      className="switch-wrapper"
    >
      <Route exact path="/" component={Home} />
      <Route path="/about/" component={About}/>
      <Route path="/etc/" component={Etc}/>
    </AnimatedSwitch>
  </Router>
)
.switch-wrapper {
  position: relative;
}

.switch-wrapper > div {
  position: absolute;
}

Docs

Limitations

This library has some obvious limitations, the most marked of which are:

  • no staggering or sequencing of animations
  • no durations or timing functions

GitHub

https://github.com/maisano/react-router-transition
Comments
  • 1. Route component mounting twice

    @maisano I can't figure out why my component appears before the transition and then it gets animated.

    Here a simple repro: https://github.com/damianobarbati/react-app

    git clone https://github.com/damianobarbati/react-app
    cd react-app 
    yarn install
    yarn serve:dev
    yarn build:dev
    

    The user app running at http://localhost:8080/user/ shows this behaviour: clicking list and then home you can see:

    1. view/picture being at left
    2. view/picture disappears
    3. view is animated sliding right to left.

    View container is position:fixed => https://github.com/damianobarbati/react-app/blob/master/apps/user/components/layout.js#L23

    What am I doing wrong? Thanks in advance for your effort with this project, I'm trying to use it in a cordova app hoping for great performance!

    Reviewed by damianobarbati at 2017-08-05 11:43
  • 2. Warning: Failed prop type: Invalid prop `styles` supplied to `TransitionMotion`.

    I started to see this after upgrading to v1. Is there a quick fix for this?

    Warning: Failed prop type: Invalid prop `styles` supplied to `TransitionMotion`.
    
    const slideLeft = {
        atEnter: {
          opacity: 0,
          offset: 100,
          pos: 0,
        },
        atLeave: {
          opacity: 0,
          offset: -100,
          pos: 2,
        },
        atActive: {
          opacity: 1,
          offset: 0,
          pos: 1,
        },
        mapStyles(styles) {
          return {
            position: (styles.pos <= 1) ? 'relative' : 'absolute',
            opacity: styles.opacity,
            transform: `translateX(${styles.offset}%)`,
          };
        },
      };
    
    <RouteTransition
    pathname={params.location.pathname}
    className="transition-wrapper"
    {...slideLeft}
     >
    <Switch key={params.location.key} location={params.location}>
      <Route path={`${match.url}/info/`} component={PatientInfoPage} />
      <Route path={`${match.url}/confirmed/`} component={ShowConfirmationPage} />
      </Switch>
    </RouteTransition>
    
    Reviewed by geryit at 2017-09-02 02:22
  • 3. still working with [email protected]?

    Reviewed by axetroy at 2017-03-17 04:28
  • 4. Does not seem to work with flex layout

    Thanks for the component! I'd like to use them in my flexbox based app. All my divs are styled as relative and with flex layout

    div, span {
      box-sizing: border-box;
      position: relative;
      border: 0 solid black;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      align-items: stretch;
      justify-content: flex-start;
      flex-shrink: 0;
    }
    

    And this is my markup that renders the children

    <div style={{height:"100vh", width: "100vw"}}>
      <div style={STYLES.appbar}></div>
      <div style={STYLES.content}>
        {children}
      </div>
      <NavBar style={STYLES.navbar}/>
    </div>
    
    const STYLES = {
      appbar: {
        flex: "none"
      },
    
      content: {
        flex: 1
      },
    
      navbar: {
        flex: "none"
      },
    }
    

    Wrapping children into ReactRouterTransition displays the old content for a moment together with the new content but then the new content jumps up to the page start (when the previous page has been removed).

    Any ideas how to get this Component to work with flexbox?

    Reviewed by pke at 2016-04-18 23:18
  • 5. Attempted import error: 'useLocation' is not exported from 'react-router-dom'

    So, I tried to get the Animated Switch working, but I got this error message. I did some research and found out that useLocation is exported from react-router, but not react-router-dom. I switched the rrt package to import from react-router instead and I got a Route that was positioned absolutely so that everything that is supposed to be beneath it was behind it.

    Basically, my footer was up where it says "Projects" image

    Reviewed by internationalhouseofdonald at 2019-11-09 23:20
  • 6. How to access your presets?

    Hello, I want to access your presets for fade, slideLeft, etc. How would I access them from the app to set the atEnter atLeave atActive? Also is react-motion accessible straight from react-router-transition in order to add custom transitions without having to install react-motion from my project?

    Reviewed by kennetpostigo at 2016-05-19 13:42
  • 7. Create-React-App Error.

    I get this error when trying to use react-router-transition with a create-react-app project.

    ./node_modules/react-router-transition/src/AnimatedRoute.js
    Module parse failed: /node_modules/react-router-transition/src/AnimatedRoute.js Unexpected token (16:49)
    You may need an appropriate loader to handle this file type.
    | }
    | 
    | const AnimatedRoute = ({ component, path, exact, ...routeTransitionProps }) => (
    |   <Route
    |     render={({ location, match }) => (
    

    i'm not quite sure what the problem is. At first i was thinking it was because of the spread operator but CRA seems to have it enabled.

    Anyone got this before ?

    Reviewed by etiennelacoursiere at 2017-09-12 17:39
  • 8. A big lag while transitioning on Android

    Hi,

    I'm facing to a big big lag on a webapp on Android 6.0.1 with an old Android System Webview.

    My RouteTransition configuration is like this:

    <RouteTransition
              className="transition-wrapper"
              pathname={this.props.location.pathname}
              atEnter={{ opacity: 0 }}
              atLeave={{ opacity: 0 }}
              atActive={{ opacity: 1 }}>
              <div className="wrapper">{childrenWithProps}</div>
    </RouteTransition>
    

    Of course:

    <div className="wrapper">{childrenWithProps}</div>
    

    is in position absolute.

    While transitioning, the computation of the opacity is extremely slow on my wrapper div and very strange... : 2016-11-22_19-24-58

    It could be endless or took lot of time.

    If anyone could help me on that hot topic for me?

    Thanks.

    Reviewed by floviolleau at 2016-11-22 18:30
  • 9. TypeScript Support

    I wanted to use the plugin on my project but couldn't find @types/react-router-transition. Is there a workaround or any plans to add support for TypeScript? Thanks in advance.

    Reviewed by TanKucukhas at 2018-05-23 14:23
  • 10. ESLint error importing module

    when I try to import the library, I get eslint errors:

    import { AnimatedSwitch } from 'react-router-transition';
    

    the errors are:

    [eslint] Unable to resolve path to module 'react-router-transition'. (import/no-unresolved)
    [eslint] Missing file extension for "react-router-transition" (import/extensions)
    

    I would love to know whats the error, so I can myself fix this with a PR. I want to contribute!

    Reviewed by horacioh at 2017-09-05 09:36
  • 11. Not sure how to send the transition container to the router

    I'm working with dave zuko's react redux starter kit and I'm trying to apply some router transitions. If I understand correctly I should wrap my component with a transitions container and send the wrapped component to my router.

    From the demo:

    const SlideRightDemo = props => (
      <RouteTransitionDemo preset={presets.slideRight} {...props} />
    );
    
    const Demo = () => (
      <Router history={hashHistory}>
        <Route path="/" component={App}>
          <Route path="slideright" component={SlideRightDemo}>
    

    Here's the router index file and a component route index:

    import CoreLayout from '../layouts/CoreLayout/CoreLayout'
    import Home from './Home'
    import CounterRoute from './Counter'
    
    export const createRoutes = (store) => ({
      path: '/',
      component: CoreLayout,
      indexRoute: Home,
      childRoutes: [
        CounterRoute(store)
      ]
    })
    

    component index

    import { injectReducer } from '../../store/reducers'
    
    export default (store) => ({
      path: 'counter',
      /*  Async getComponent is only invoked when route matches   */
      getComponent (nextState, cb) {
        /*  Webpack - use 'require.ensure' to create a split point
            and embed an async module loader (jsonp) when bundling   */
        require.ensure([], (require) => {
          /*  Webpack - use require callback to define
              dependencies for bundling   */
          const Counter = require('./containers/CounterContainer').default
          const reducer = require('./modules/counter').default
    
          /*  Add the reducer to the store on key 'counter'  */
          injectReducer(store, { key: 'counter', reducer })
    
          /*  Return getComponent   */
          cb(null, Counter)
    
        /* Webpack named bundle   */
        }, 'counter')
      }
    })
    
    Reviewed by sschenk at 2016-08-07 17:15
  • 12. Attempted import error: 'Switch' is not exported from 'react-router-dom'

    After downloding , "react-router-dom": "^6.0.0-beta.8", Switch is not available anymore. So my this code fire error.

    import React from "react";
    import { BrowserRouter, Routes, Route } from "react-router-dom";
    import { AnimatedSwitch } from "react-router-transition";
    
    import routes from "./routes";
    
    const RouterProvider = () => (
      <BrowserRouter>
        <Routes>
          <AnimatedSwitch
            atEnter={{ opacity: 0 }}
            atLeave={{ opacity: 0 }}
            atActive={{ opacity: 1 }}
            className="switch-wrapper"
          >
            {routes.map((route) => (
              <Route key={route.path} path={route.path} element={route.component} />
            ))}
          </AnimatedSwitch>
        </Routes>
      </BrowserRouter>
    );
    
    export default RouterProvider;
    
    

    My error is **./node_modules/react-router-transition/lib/index.js Attempted import error: 'Switch' is not exported from 'react-router-dom'. ** is there any way to fix it?

    Reviewed by sayinmehmet47 at 2021-11-11 22:16
  • 13. Notifying transitioned component that transition has started (instead of ComponentWillUnmount)

    Hi,

    I've added this great package to an existing project where "componentWillUnmount" was used to clean all kinds of resources / listeners. Problem is, now, in my flow, an action occurs, which navigates the user outside of the Component, but a re-render also happens. Usually, without the animation, the component would immediately run "componentWillUnmount" and release all the need for re-renders.. But, now, during the animation bad / unexpcted things happen.

    I suggest to add some hook / callback to each such "transitioned" component (e.g. "transitionStarted") to allow it to cleanup sooner, instead of using componentWillUnmount.

    Reviewed by doron-au10tix at 2021-07-25 06:21
  • 14. Support "prefers-reduced-motion"

    https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion

    If the OS has reduced-motion turned on then the transition still happens. It would be nice if the transition was disabled if reduced-motion was set.

    Reviewed by Jivings at 2021-06-30 10:53
  • 15. Is there any way to add/remove classes `atEnter`, `atLeave`, and `atActive`?

    I'm attempting to add/remove a .hide class:

    .hide {
        margin: 0; 
        padding: 0; 
        width: 0; 
        height: 0; 
        opacity: 0; 
    }
    

    Which essentially allows other elements to pass over the corresponding element in its atLeave state, of course given that element has this class. Then, on this element's atEnter stage, I must promptly remove this class.

    Is there any known way of doing this?

    Reviewed by Lathryx at 2021-03-18 19:21
  • 16. Update to React version 17.X?

    Would love to use this package, but my React version is 17.0.1 (I'm using the latest version of Create React App). I'm gonna fork the package and update it for now, but it would be great to have it supported directly.

    Reviewed by finnmerlett at 2021-02-20 14:23
Suspense like transitions for react

@n1ru4l/react-use-transition Suspense like transitions without experimental react features today. For any fetching library. Why? Ever experienced flas

Nov 8, 2021
A wrapper over Motion One, An animation library, built on the Web Animations API for the smallest filesize and the fastest performance

A wrapper over Motion One, An animation library, built on the Web Animations API for the smallest filesize and the fastest performance. Works with solid-js

May 17, 2022
Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height
Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height

Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height

May 2, 2022
Framer motion demo with React

Creating modals in React Framer Motion Features Installation Set up Live Demo What is Framer Motion? Framer Motion is a relatively new open source, pr

May 4, 2022
React Shoe - a project developed to study the Three.js technology for 3d objects and framer motion for 2d animations
React Shoe - a project developed to study the Three.js technology for 3d objects and framer motion for 2d animations

React Shoe - a project developed to study the Three.js technology for 3d objects and framer motion for 2d animations

Apr 30, 2022
📷 A flexible image gallery lightbox with native-feeling touch gestures and buttery smooth animations, built with react-spring.
📷 A flexible image gallery lightbox with native-feeling touch gestures and buttery smooth animations, built with react-spring.

react-spring-lightbox React-spring-lightbox is a flexible image gallery lightbox with native-feeling touch gestures and buttery smooth animations. Doc

May 14, 2022
Planets fact site with animated solar system built with ReactJS.
Planets fact site with animated solar system built with ReactJS.

Frontend Mentor - Planets fact site Table of contents Overview Intro The challenge Links My process Built with Features Setup Useful resources Overvie

Mar 15, 2022
React components for the Web Animations API - http://react-web-animation.surge.sh
React components for the Web Animations API - http://react-web-animation.surge.sh

react-web-animation react-web-animation is a set of React components that expose the Web Animations API in a declarative way. Demos Check out how you

Mar 19, 2022
A React library to work with lottie animations inside React.js

React Lottie Tools This React library helps to work with lottie animations inside React.js Info This library is an abstraction of the official lottie

Feb 3, 2022
react-animated-numbers - 👾 Library showing animation of number changes in react.js

react-animated-numbers - ?? Library showing animation of number changes in react.js

May 17, 2022
React App with games using animations (react-spring)
React App with games using animations (react-spring)

Teddy games https://pylnata.github.io/teddy/ React App with cartoon animations and games for kids. Developed just for fun and to learn React-spring li

May 10, 2022
Animated sidebar using react , react icon

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Jan 17, 2022
Project build: REACT CREATE APP / REDUX / REDUX-TOOLKIT / REACT-SPRING / SCSS

This project was bootstrapped with Create React App, using the Redux and Redux Toolkit template. designed by Om Arya Available Scripts In the project

Mar 21, 2022
React-animate-style - A react integration of animate.css (animate.style)

react-animate-style Easy animate react app with animate.css library Install With

Jan 31, 2022
Animation engine designed for React
Animation engine designed for React

react-tweenful Looking for an amazing React library for animating stuff? Look no more, we've got you covered! Demo https://teodosii.github.io/react-tw

May 11, 2022
Easily animate your data in react

data-driven-motion Easily animate your data in react This is a small wrapper around react-motion with the intention of simplifying the api for my most

Mar 24, 2022
(ノ´ヮ´)ノ*:・゚✧ A super easy animation library for React!

react-anime (ノ´ヮ´)ノ*:・゚✧ A super easy animation library for React built on top of Julian Garnier's anime.js. Just place an <Anime> component and what

May 4, 2022
Use the full power of React and GSAP together

react-gsap-enhancer Demos Why? How it works? Usage API A React component enhancer for applying GSAP animations on components without side effects. For

May 11, 2022
react-magic-move - MagicMove wrapper.

React Magic Move Magic Move for React.JS NOT A PRODUCTION MODULE This was just a fun experiment, with some love, it could definitely be a real thing,

May 13, 2022