Julia Pottinger
0

Scroll to Top - React & Gatsby

July 02, 2020

One thing that I love to see on websites when you scroll is a beautifully placed scroll to top button. It is a very helpful navigation that brings the user to the top of a page without them having to scroll all the way up. On a blog it is very useful. When creating my blog with Gatsby this was one of my must have features. In this blog post I will be sharing with you the steps that I took to implement the scroll feature on my blog site.

The first thing that we are going to do is install our dependencies. For this feature I used MaterialUI. You can use any UI helper that you choose as the core of this feature will remain the same.

npm install --save @material-ui/core
npm install --save @material-ui/icons

We are going to then create our scroll component. We start by importing our dependencies. We will be using the ExpandLess icon from MaterialUI.

import React, { useState, useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import ExpandLessIcon from '@material-ui/icons/ExpandLess';
import IconButton from '@material-ui/core/IconButton';

We will next be returning our icon that we want to use.

const Scroll = ({}) => {
    return (
        <div>
            {show &&
                <IconButton onClick={handleClick} className={classes.toTop} aria-label="to top" component="span">
                    <ExpandLessIcon />
                </IconButton>
            }
        </div>
    )
}
export default Scroll

The above code has a condition that if show is true then you show the toTopIcon.

Let us now add some more functionality to this. You are going to accept a parameter in your scroll component called showBelow. We will use this parameter to determine if show should be true or false.

We will also create a function to handleClick and handleScroll. Additionally we will be using React useState and useEffect respectively to manage the state of show and add a scroll listener to the window.

const Scroll = ({
    showBelow,
}) => {

    const classes = useStyles();

    const [show, setShow] = useState(showBelow ? false : true)

    const handleScroll = () => {
        if (window.pageYOffset > showBelow) {
            if (!show) setShow(true)
        } else {
            if (show) setShow(false)
        }
    }

    const handleClick = () => {
        window[`scrollTo`]({ top: 0, behavior: `smooth` })
    }

    useEffect(() => {
        if (showBelow) {
            window.addEventListener(`scroll`, handleScroll)
            return () => window.removeEventListener(`scroll`, handleScroll)
        }
    })

    return (
        <div>
            {show &&
                <IconButton onClick={handleClick} className={classes.toTop} aria-label="to top" component="span">
                    <ExpandLessIcon />
                </IconButton>
            }
        </div>
    )
}
export default Scroll

We are now going to add styling to the button so that it appears where we want it to. Add the following snippet of code directly after your imports and before the Scroll component

const useStyles = makeStyles((theme) => ({
    toTop: {
        zIndex: 2,
        position: 'fixed',
        bottom: '2vh',
        backgroundColor: '#DCDCDC',
        color: 'black',
        "&:hover, &.Mui-focusVisible": {
            transition: '0.3s',
            color: '#397BA6',
            backgroundColor: '#DCDCDC'
        },
        [theme.breakpoints.up('xs')]: {
            right: '5%',
            backgroundColor: 'rgb(220,220,220,0.7)',
        },
        [theme.breakpoints.up('lg')]: {
            right: '6.5%',
        },
    }
})
)

Our component is now styled and will show to the bottom right of the page once it meets the required scroll height.

Finally we are now going to add this component to your page. I recommend that you add it to your gatsby layout.js file so that it is used on all pages.

Import the Scroll component

import Scroll from '../components/scroll'

And then call it and pass in the showBelow parameter that you want it to be triggered on.

<Scroll showBelow={250} />

If you take a look to the right of this page you should see the scroll to top button on this blog.

I hope that this blog was very helpful and you successfully implemented the scroll to top functionality on your Gatsby React blog. If you are interested in a scroll to the bottom button you can set your handleClick functionality to the following and it should scroll to the bottom of the page.

const handleClick = () => {
        window[`scrollTo`]({ top: document.body.scrollHeight, behavior: `smooth` })
    }

You will also need to update the css to position the button at the top as well as change the icon. If you have any questions or issues leave a comment or use the contact form. All the best.

View the Video Tutorial for this blog.


Written by Julia Pottinger who lives and works in Jamaica building useful things. Follow her on Twitter and check out her YouTube Channel

Sign up for Newsletter

Share this blog

© 2020 Julia Pottinger - All Rights Reserved