Gatsby.js & Parallax

Setting up parallax with Gratsby.js & Prismic

Last year I was working on a history page that would showcase a list of achievements and milestones over the last 30 odd years that one of our clients had reached. There was a lot of content and we wanted to feature it in an exciting way. Here’s the final product. Let's get straight into it and talk about creating parallax in Gatsby.js!

gatsby-browser.js

Working with Gatsby can be tricky at times as a frontend developer because since it’s a static site generator that creates your site during the build phase you can’t reference the window object like you’re used to. Parallax is all about scrolling so you need this reference and that’s where the gatsby-browser.js come is. It lets you respond to actions within the browser, and wrap your site in additional components, which is exactly what’s happening in the code above. We import our parallax library and wrap our page element with it.

Managing Content

I’m a big fan of Prismic and their simplistic methodology of grouping content into single and repeatable types makes this task a breeze. This page was architected by creating a single type of history page, where all the general page information could be kept. Then inside of this type, we initialize the slice-zone, which is basically just content components that you can pre-define. My slice is called the timeline section. Inside the slice-zone, we again have the option of placing our content into single or repeatable buckets. I’m going to give my slice zone a nonrepeatable property of year and then within the repeatable zone an image, secondary image, description, and a select dropdown that will toggle the size of our desired text. So back in our Gatsby app, our graphQL query is going to look something like this.

Rendering Content

Now that we have all our content in place let’s render it on the page. First, don’t forget to install our parallax package.

npm i react-scroll-parallax

This package is pretty straight forward to use. You just have to feed each element an X and Y coordinate like so.

I’m using styled comments here which makes it super easy to add a little more logic to your parallax, such as checking odd and even indexes on the array and then adjusting the styles accordingly to have the content ping pong from left to right. I recently wrote a parallax page from scratch, which is a fun exercise, but for the most part, It feels like this react parallax package is completely sufficient for our purposes.

The author of this tutorial is Kahil Nayton, a Frontend Engineer based out of NYC.

Full stack developer based out of Brooklyn, NYC.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store