Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

323
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda