Reputation: 643
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?
Upvotes: 13
Views: 11565
Reputation: 41
This should work
import { navigate } from "@gatsbyjs/reach-router";
<button onClick={() => navigate(-1)}>Back to previous page</button>
It goes to the previous page
Upvotes: 0
Reputation: 8678
Use navigate(-1)
:
import React from "react";
import { navigate } from "gatsby";
export default function GoBack() {
return (
<Button onClick={() => navigate(-1)}>
Go Back
</Button>
);
}
Upvotes: 20
Reputation: 11
The gatsby navigate function is type as NavigateFn.
Which you can find declare as:
export interface NavigateFn {
(to: string, options?: NavigateOptions<{}>): Promise<void>;
(to: number): Promise<void>;
}
So, as you can see, you either can pass the route you want to redirect to, or an specific number.
Try with navigate(-1)
Upvotes: 1
Reputation: 51
For a function component in Gatsby:
<a onClick={() => window.history.back()}>Go back</a>
Upvotes: 1
Reputation: 11577
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>
)
Upvotes: 8