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.