Enea Xharja

Smooth Scrolling in Gatsby

The following guide describes how to implement smooth scrolling in Gatsby using the smooth-scroll package.

Instructions

  1. add the package to your project:
npm install --save smooth-scroll
  1. in your layout.js component, import the smooth-scroll package after the import statements but just before the component is rendered:
if (typeof window !== 'undefined') {
  require('smooth-scroll')('a[href*="#"]');
}
  1. add the id property to the element on the page you want to navigate to:
<InfoSection id="info" />
  1. use Gatsby Link to navigate to the desired section of the page:
<Link to="#info">More Info</Link>

The approach described above works if you are trying to link to elements on the same page. However, if you want to implement smooth scrolling for every page, you need to use the Location component from Reach Router in order to access the current location via a render prop.

Updated on January 29, 2021

Tagged with: gatsby, snippets


Profile picture

Hey there! I'm Enea, a web developer currently working at eqolot. Welcome to my little corner of the web, where I share my personal collection of notes, code snippets, and resources on topics that interest me.

© 2021 Enea Xharja