I'd like to scroll to a given horizontal position in an element immediately after it's rendered by React. For context, I'm using Next.js with server-side rendering, so useLayoutEffect
isn't an option.
export default function WideElement () {
const ref = useRef(null)
useEffect(function () {
ref.current.scrollLeft = 1000
}, [])
return (
<Container ref={ref}>
...
</Container>
)
}
However, the above code doesn't scroll when the page loads. Here the ...
represents a long list of child elements that stack horizontally and overflow the container.
I have noticed that if I impose an artificial delay on the scroll, it seems to work fine, and Container
is immediately scrolled 1000 pixels to the left.
export default function WideElement () {
const ref = useRef(null)
useEffect(function () {
setTimeout(function() {
ref.current.scrollLeft = 1000
}, 1000)
}, [])
return (
<Container ref={ref}>
...
</Container>
)
}
I think I might be misunderstanding useEffect
. What am I missing, and how could I make this work?