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>
)
1.3.0
. Usenavigate(-1)
– Mabe