Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I go to previous page in gatsby (history.goBack)

I am working on gatsby. I need to go back to privious page/link as I used to do with reactjs.

<a onClick={() => this.props.history.goBack}>
  <button type="button" className="close_tab">
    <img src={Close} alt="" />
  </button>
</a>

How can I do this using gatsby?

like image 407
Profer Avatar asked May 02 '19 13:05

Profer


3 Answers

Use navigate(-1):

import React from "react";
import { navigate } from "gatsby";

export default function GoBack() {
  return (
    <Button onClick={() => navigate(-1)}>
      Go Back
    </Button>
  );
}
like image 180
Steve Bauman Avatar answered Nov 06 '22 22:11

Steve Bauman


Edit: Since [email protected], you can now simply call navigate(-1) to go back. Manually update reach-router in your Gatsby project if it's not yet updated. Thanks @nathan in the comment for the tip.


Edit: Ah alright, I've just realized this.props.history.goBack is a react-router thing. Gatsby doesn't use react-router, but reach-router under the hood and it doesn't have the history props or the goBack method. There's a issue requesting to add this, but wasn't implemented. You'd have to use browser's own history object as I suggested below.

import React from 'react'

const BackButton = React.forwardRef(
  ({ children, ...props }, ref) => {
    const onClick = e => {
      e.preventDefault()
      history.back()
    }
    return (
      <a {...props} ref={ref} href="#" onClick={onClick}>
        {children}
      </a>
    )
  }
)

BackButton.displayName = 'BackButton'
export { BackButton }

Is this.props.history the browser's history? If so, you can do this.props.history.go(-1) to go back to the previous page.

As always with Gatsby, watch out when you use methods from browser, since they don't exist during html generation:

export default () => (
  <button onClick={() => {
    typeof history !== 'undefined' && history.go(-1)
  }}>back</button>
)
like image 43
Derek Nguyen Avatar answered Nov 06 '22 22:11

Derek Nguyen


For a function component in Gatsby:

   <a onClick={() => window.history.back()}>Go back</a>
like image 24
Verner Keel Avatar answered Nov 06 '22 22:11

Verner Keel