0

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>
  );
}
coreyward
  • 77,547
  • 20
  • 137
  • 166
Tasha Zuniga
  • 33
  • 1
  • 2
  • 5
  • Did you ever find the solution? I have a similar problem where I get "This page is not created yet" as soon as I use the navigate() function. – mraxus Nov 24 '20 at 13:54

2 Answers2

2

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>
coreyward
  • 77,547
  • 20
  • 137
  • 166
0

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

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

not

navigate(-1)