Renato
Renato

Reputation: 121

Next/React hot to use router.back() cascade and ignoring anchor links

I'm developing my own blog website with Next.js and MD transcriptions. I'm having a problem with anchor links. All my titles <h1> become anchor links using next Link component:

<Link passHref href={"#" + anchor.href}>{anchor.name}</Link>

In this way the anchor links work fine. But when I enter in a anchor link and then press the back button (from the browser or the router.back()) instead of returning to the page that I came from, it just return to the link without the anchor link # or to the last anchor link that I clicked.

There is a way that I can go back in cascade without the need to push to the last page? If I came from a blog post X to a blog post Y, how could I go back until reach this X post? I thought about using react-router to make this kind of cascade, but don't know if would work.

Here's the website, I will try to put the last version online until post this.

The way that I do router.back is this one:

// The router
import { useRouter } from 'next/router';
const router = useRouter();

// the JSX

<div variants={slideButtonDown} style={{margin: ".5rem 0"}}>
    <CustomButton description='Return to Blog page' text='' 
     icon{ButtonIcon.arrowBack} onClick={() => {router.back()}}/>
</div>

If someone have any idea of how could I improve it, it would help a lot

OBS: I use static generated website with static props and paths.

Upvotes: 0

Views: 1523

Answers (1)

Sabrina Luo
Sabrina Luo

Reputation: 4000

The default behavior of the Link component is to push a new URL into the history stack. You can use the replace prop to prevent adding a new entry, as in the following example:

<Link passHref href={"#" + anchor.href} replace>{anchor.name}</Link>

ref: https://nextjs.org/docs/api-reference/next/link#replace-the-url-instead-of-push

Upvotes: 1

Related Questions