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?
Use navigate(-1)
:
import React from "react";
import { navigate } from "gatsby";
export default function GoBack() {
return (
<Button onClick={() => navigate(-1)}>
Go Back
</Button>
);
}
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>
)
For a function component in Gatsby:
<a onClick={() => window.history.back()}>Go back</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With