Josh Cuneo

Gatsby - Animating Page Transitions

February 03, 2019

Animations in React can be a little tricky and Gatsby adds another layer of complexity with it’s abstracted routing. This is my current method for animating page transitions in Gatsby using React Pose.

Install Dependencies

npm i react-pose

Create Transition Component

We will use a PoseGroup to animate our page transitions. First we need to create the ‘Transition’ component.

touch src/components/Transition.js
import React from "react";
import posed, { PoseGroup } from "react-pose";

const timeout = 0;

class Transition extends React.PureComponent {
  render() {
    const { children, location } = this.props;

    const RoutesContainer = posed.div({
      enter: {
        opacity: 1,
        filter: "blur(0px)",
        y: 0,
        delay: timeout,
        delayChildren: timeout
      },
      exit: {
        opacity: 0,
        filter: "blur(20px)",
        y: 30
      }
    });

    return (
      <PoseGroup>
        <RoutesContainer key={location.pathname}>{children}</RoutesContainer>
      </PoseGroup>
    );
  }
}

export default Transition;

Change the timeout value to adjust the animation timing and checkout out the React Pose docs for different animation options.

Wrap Pages In Transition

We will make use of two Gatsby APIs to wrap our pages in the transition both during server rendering and in the browser.

// gatsby-browser.js

/**
 * Implement Gatsby's Browser APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/browser-apis/
 */

// You can delete this file if you're not using it
import React from "react";
import Transition from "./src/components/Transition";

export const wrapPageElement = ({ element, props }) => {
  return <Transition {...props}>{element}</Transition>;
};
// gatsby-ssr.js

/**
 * Implement Gatsby's SSR (Server Side Rendering) APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/ssr-apis/
 */

// You can delete this file if you're not using it
import React from "react";
import Transition from "./src/components/Transition";

export const wrapPageElement = ({ element, props }) => {
  return <Transition {...props}>{element}</Transition>;
};

Done!


Josh Cuneo

Handy reminders of things I've discovered learning web development. Collected by me as I live, work and parent in Wollongong, NSW.
Get in touch by email.
Or follow me on twitter.

General library plugs