Next.js Discord

Discord Forum

<Link> that goes back a page and scrolls to previous position

Answered
Savannah posted this in #help-forum
Open in Discord
SavannahOP
I have a link tag that goes back one route:

<Link href="..">Go back</Link>


When user presses it, he goes back but the user viewport is always on top. I need it to scroll back where it was like if user pressed "go back" in the browser itself. How can I do that?
Answered by joulev
hmm try instead of using <Link>, use a normal button and in onClick, you use router.back()
View full answer

7 Replies

SavannahOP
So, no help?
Answer
SavannahOP
Yep, it works
@joulev hmm try instead of using `<Link>`, use a normal button and in `onClick`, you use `router.back()`
SavannahOP
What about SEO though? How can I let crawlers know that this is a link and not just a button
@Savannah What about SEO though? How can I let crawlers know that this is a link and not just a button
then try this, not sure if it works though
() => <Link
  href="..."
  onClick={e => {
    e.preventDefault();
    router.back();
  }}
>
  Go back
</Link>
@joulev then try this, not sure if it works though tsx () => <Link href="..." onClick={e => { e.preventDefault(); router.back(); }} > Go back </Link>
SavannahOP
Yes, this seems to work properly. At least it scrolls and there are no errors in the console. Here's the component I've created for the scroll:

"use client"

import { useRouter } from "next/navigation"
import commonStyles from "@/styles/common.module.css"
import Link from "next/link"

export default function LinkBack({ children }: React.PropsWithChildren) {
  const router = useRouter()

  return (
    <Link
      href=".."
      className={commonStyles.link_button}
      onClick={e => {
        e.preventDefault()
        router.back()
      }}
    >{children}</Link>
  )
}