Reputation: 519
I'm using Next.js for my application and I'm facing some issues on routing to the previous route of the application. I'm aware of the router function back()
which is similar to window.history.back()
, I would like to go back to the route when a Link
is clicked, and if the previous link isn't from my application or is null
, I would like to go to the home page as a default.
I used libraries like react-router-last-location
for my react app, but I wanna see if there are better ways to do it in Next.js via next/router
.
Here is my sample code:
<div className={styles['icon-container']}>
<Link href="/"><a>
<img src="icon.svg"></img>
</a></Link>
</div>
if i use router.back() in the href input, the page goes back automatically even before it loads, how do i solve this issue?
Upvotes: 2
Views: 31430
Reputation: 879
The solution offered here does not work for newer versions of next.js. There have been several changes (see the documentation):
useRouter
from next/navigation
'use client';
The easiest way is to create a component BackButton.tsx
similar to the following:
'use client';
import {useRouter} from 'next/navigation';
export default function BackButton() {
const router = useRouter();
return (
<button onClick={router.back}>back</button>
)
}
and then inside your page import the BackButton
as shown by this example:
import BackButton from "@/components/BackButton";
export default function Home() {
return (
<main className="flex min-h-screen flex-col p-12">
<h1>[<BackButton/>] Title</h1>
// ... whatever else you have ...
</main>
);
}
Upvotes: 2
Reputation: 511
<Link>
can't go outside of your app. (but router.back()
can)
You can't use router.back()
directly in the code, you need to do something like :
<img onClick={router.back} src="icon.svg" />
<Link>
does not have onClick property.
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={router.back}>
Click here to go back
</button>
)
}
Source of info here
Upvotes: 13