Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

330
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda