Similar to this post, my case doesn't use React Router or jQuery. It's just a single page and vertically long. As for the title, anchor links don't jump to the accurate position since the images are not loaded and cannot calculate the precise location. I found a solution and tried as below, but not working. How can I solve it?
UPDATE: As in the comment, setting image sizes didn't work either.
export const useScrollToLocation = () => {
const scrolledRef = useRef(false)
const { hash } = useLocation()
const hashRef = useRef(hash)
useEffect(() => {
if (hash) {
// We want to reset if the hash has changed
if (hashRef.current !== hash) {
hashRef.current = hash
scrolledRef.current = false
}
// only attempt to scroll if we haven't yet (this could have just reset above if hash changed)
if (!scrolledRef.current) {
const id = hash.replace('#', '')
const element = document.getElementById(id)
if (element) {
element.scrollIntoView({ behavior: 'smooth' })
scrolledRef.current = true
}
}
}
})
}
function App() {
return (
<>
<useScrollToLocation>
<Navigation />
<Hero />
<Concept />
<Shop />
<Footer />
</useScrollToLocation>
</>
)
}
export default App