'The Use of "Navigate(-1)" Fails to Return to Previous Location in Gatsby

I am trying to create a simple "Back" button in Gatsby that returns the the previous page and retains the scroll position. This already happens when using the browser back button, but I'm struggling to produce a custom one. I've read in the Reach Router docs that you can add -1 as an argument to the navigate function to return to previous locations, but It instead throws the number value into the url and gives me a 404. Can someone give me an idea of what I've done wrong? Or if anyone else has managed to make a functional back button for Gatsby projects?

Here is my code-

import React from 'react';
import { graphql, navigate } from 'gatsby'
import Img from "gatsby-image"

import "./design.scss"

const designTemplate = (props) => {
  return (
      <section className="design">
        <div className="design__container">
        <h2 className="design__title">
          {props.data.design.title}
        </h2>
        <Img className="design__image" fluid={props.data.design.localImage.childImageSharp.fluid} />
        <p className="design__summary">
          {props.data.design.summary}
        </p>
        </div>
        <button onClick={navigate(-1)}>Go Back</button>
      </section>
  );
}


Solution 1:[1]

The issue you're having here is just that you didn't define a callback function for your onClick handler.

Instead of this:

<button onClick={navigate(-1)}>Go Back</button>

…you want to do this:

<button onClick={() => { navigate(-1) }}>Go Back</button>

Solution 2:[2]

Your onClick must have a callback(arrow function) like this

onClick={()=>{navigate(-1)}}

not

navigate(-1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 coreyward
Solution 2 Fahad