Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

325
Views
How to animate scroll to #id element with router.replace in Next.js?

I have basically this in React/Next.js:

import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'

const LETTERS = ['a', 'b', 'c']

export default function MyComponent() {
  const router = useRouter()
  const [selectedLetter, setSelectedLetter] = useState(LETTERS[0])

  useEffect(() => {
    if (selectedLetter) {
      const hash = `${selectedLetter}-letter`
      const el = document.querySelector(`#${hash}`)
      el?.scrollIntoView({ behavior: 'smooth' });
      router.replace(`${window.location.pathname}#${hash}`, null, { shallow: true })
    }
  }, [selectedLetter])

  const cycleLetter = () => {
    let i = LETTERS.indexOf(selectedLetter)
    if (i === LETTERS.length - 1) {
      i = 0
    } else {
      i = i + 1
    }
    setSelectedLetter(LETTERS[i])
  }

  return (
    <div>
      <button onClick={cycleLetter}>next letter</button>
      {LETTERS.map(letter => <h2 id={`${letter}-letter`}>{letter} section...</h2>)}
    </div>
  )
}

When I click "next letter", it does navigate to the right <h2 id="b-letter"> sort of thing, but no animation. How do I make it animate scrollIntoView in the proper next.js way? If I comment out the router.replace..., it properly animates, but I want the route to be reflected in the URL for easy copy/paste/linking. How to disable the default browser behavior I guess, and animate even though the route might change the hash?

Is my only option just to not use the hash #? I guess I could use a query search param as well.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!