Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save johnnybenson/71e197e7ae3786107394158ccd0ecec1 to your computer and use it in GitHub Desktop.
Save johnnybenson/71e197e7ae3786107394158ccd0ecec1 to your computer and use it in GitHub Desktop.
React Router v5 TransitionGroup CSSTransition Directional Animation with CSS Modules
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import styles from './styles.module.scss';
const TRANSITIONS = {
PUSH: {
enter: styles.LeftEnter,
enterActive: styles.LeftEnterActive,
exit: styles.LeftExit,
exitActive: styles.LeftExitActive,
},
POP: {
enter: styles.RightEnter,
enterActive: styles.RightEnterActive,
exit: styles.RightExit,
exitActive: styles.RightExitActive,
},
};
const TRANSITION_DURATION = 500;
export default function RouteTransition({ children }) {
return (
<Route
render={({ location, history }) => {
return (
<TransitionGroup className={styles.Transition}>
<CSSTransition
key={location.key}
classNames={TRANSITIONS[history.action]}
mountOnEnter={true}
timeout={TRANSITION_DURATION}
className={styles.Transition}
>
<Switch location={location}>{children}</Switch>
</CSSTransition>
</TransitionGroup>
);
}}
/>
);
}
@johnnybenson
Copy link
Author

.Transition {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

.LeftEnter {
  transform: translate(100%, 0);
}
.LeftEnterActive {
  transform: translate(0, 0);
  transition: transform 200ms;
}
.LeftExit {
  transform: translate(0, 0);
}
.LeftExitActive {
  transform: translate(-100%, 0);
  transition: transform 200ms;
}

.RightEnter {
  transform: translate(-100%, 0);
}
.RightEnterActive {
  transform: translate(0, 0);
  transition: transform 200ms;
}
.RightExit {
  transform: translate(0, 0);
}
.RightExitActive {
  transform: translate(100%, 0);
  transition: transform 200ms;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment