Animating page transitions in Gatsby

Animating page transitions in Gatsby

Motivation πŸ”₯

I’m totally enjoying Gatsby for various reasons and in this post I want to share how easy it is to add customized page transitions to your website to make it more lively and smooth.

We will be using Gatsby default starter to make this example as isolated as possible but you can be sure that it will also work for more complex starters and projects created by you from the scratch.

As a teaser, we will build something similar to what you see when you follow links on this siteπŸ˜ƒ

Getting started πŸ› οΈ

If you are new to Gatsby and want to follow along this tutorial be sure to install Gatsby command line interface(Gatsby CLI) so you can quickly bootstrap new projects in the future.

1npm install --global gatsby-cli
Copy

Navigate to your project folder and create new Gatsby project inside of it by running the following command in the terminal:

1gatsby new .
Copy

It will create a project with simplest possible setup and it should look like this: (it may vary for the further iterations on starter’s design)

An image

Installing necessary dependencies βš™οΈ

First of all we need to install react-transition-groupwhich is responsible for watching out for elements entering and leaving the DOM and applying animations to them.

npm install react-transition-group

We will also install gatsby-plugin-layout that in our case serves the purpose of providing location property required for transitions to work and injects our layout to every page.

npm install gatsby-plugin-layout

To make plugin work as expected we need to move our layout component into layouts folder at the root of our project and rename it to index.js. Let’s also add transition.js to our components folder where we will supply all the transition logic. For now leave it empty as we have a little more to configureπŸ˜„

src
tree
1 β”œβ”€β”€ components
Copy
2 β”‚Β Β  β”œβ”€β”€ header.js
3 β”‚Β Β  β”œβ”€β”€ image.js
4 β”‚Β Β  └── transition.js
5 β”œβ”€β”€ images
6 β”‚Β Β  β”œβ”€β”€ gatsby-astronaut.png
7 β”‚Β Β  └── gatsby-icon.png
8 β”œβ”€β”€ layouts
9 β”‚Β Β  β”œβ”€β”€ index.js
10 β”‚Β Β  └── layout.css
11 └── pages
12 β”œβ”€β”€ 404.js
13 β”œβ”€β”€ index.js
14 └── page-2.js

Last step is adding our gatsby-plugin-layout to gatsby-config.js file that is located in the root of our project

gatsby-config.js
js
1plugins
Copy
:
Copy
Copy
[
Copy
Copy
2 'gatsby-plugin-react-helmet',
3 {
4 resolve: `gatsby-source-filesystem`,
5 options: {
6 name: `images`,
7 path: `${__dirname}/src/images`,
8 },
9 },
10 'gatsby-plugin-layout',
11 'gatsby-transformer-sharp',
12 'gatsby-plugin-sharp',

Transition component 🎩

It holds the full logic for transition that will be applied when user decides to follow a link to other page on our site.

Inside transition.js add the following code which I will explain in comments:

transition.jsx
jsx
1//Import necessary dependencies
Copy
Copy
2
3import React from 'react'
4import {
5 TransitionGroup,
6 Transition as ReactTransition,
7} from 'react-transition-group'
8
9//This variable will be responsible for our animation duration
10const timeout = 500
11
12//This object contains basic styles for animation, but you can extend them to whatever you like. Be creative!
13const getTransitionStyles = {
14 entering: {
15 position: 'absolute',
16 opacity: 0,
17 },
18 entered: {
19 transition: `opacity ${timeout}ms ease-in-out`,
20 opacity: 1,
21 },
22 exiting: {
23 transition: `all ${timeout}ms ease-in-out`,
24 opacity: 0,
25 },
26}
27
28class Transition extends React.PureComponent {
29 render() {
30 //Destructuring props to avoid garbage this.props... in return statement
31 const { children, location } = this.props
32
33 return (
34 //Using TransitionGroup and ReactTransition which are both
35 //coming from 'react-transition-group' and are required for transitions to work
36 <TransitionGroup>
37 <ReactTransition
38 //the key is necessary here because our ReactTransition needs to know when pages are entering/exiting the DOM
39 key={location.pathname}
40 //duration of transition
41 timeout={{
42 enter: timeout,
43 exit: timeout,
44 }}
45 >
46 {//Application of the styles depending on the status of page(entering, exiting, entered) in the DOM
47 status => (
48 <div
49 style={{
50 ...getTransitionStyles[status],
51 }}
52 >
53 {children}
54 </div>
55 )}
56 </ReactTransition>
57 </TransitionGroup>
58 )
59 }
60}
61
62export default Transition

Now we can import Transition component into Layout component and wrap children which represent our pages inside of it.

layout.jsx
jsx
1//Note that we need to pass location to our functional component so we have access to it down there in <Transition/>
Copy
Copy
2const Layout = ({ children, location }) => (
3 <StaticQuery
4 query={graphql`
5 query SiteTitleQuery {
6 site {
7 siteMetadata {
8 title
9 }
10 }
11 }
12 `}
13 render={data => (
14 <>
15 <Helmet
16 title={data.site.siteMetadata.title}
17 meta={[
18 { name: 'description', content: 'Sample' },
19 { name: 'keywords', content: 'sample, something' },
20 ]}
21 >
22 <html lang="en" />
23 </Helmet>
24 <Header siteTitle={data.site.siteMetadata.title} />
25
26 <Transition location={location}>{children}</Transition>
27 </>
28 )}
29 />
30)
31
32Layout.propTypes = {
33 children: PropTypes.node.isRequired,
34}
35
36export default Layout

At this point you may experience a bug when some of your page elements being rendered twice. To solve that just go trough files in pages folder and make sure that they don’t import <Layout> component and use in return statement.

Now that everything is working as expected and you are enjoying your newly added page transitions you may notice a slight jerky bug that appears when your page is being scrolled down and animation starts. Note that it happens when there is more content on the page and you can scroll.

We can easily fix this with the help of including this code in our gatsby-browser.js which you can find in the root of our project. What we do here is actually setting time out for animation and waiting for it to be executed until page scrolls to the top.

gatsby-browser.js
js
1const
Copy
transitionDelay
Copy
=
Copy
Copy
500
Copy
Copy
2
3exports.shouldUpdateScroll = ({
4 routerProps: { location },
5 getSavedScrollPosition,
6}) => {
7 if (location.action === 'PUSH') {
8 window.setTimeout(() => window.scrollTo(0, 0), transitionDelay)
9 } else {
10 const savedPosition = getSavedScrollPosition(location)
11 window.setTimeout(
12 () => window.scrollTo(...(savedPosition || [0, 0])),
13 transitionDelay
14 )
15 }
16 return false
17}

I hope you’ve enjoyed this small post and will use your new knowledge whenever you need it. Here you can find a link to GitHub repo with the working code for this tutorial.


Comments section

Dimitri Ivashchuk

Written by Dimitri who lives and works in Vienna building useful things. He is passionate about modern web technologies and enjoys learning something new everyday as well as sharing his knowledge with others.

Front-end engineer @CubeTech
Instructor @egghead.io