Reputation: 157
const ref = useRef(null);
const executeScroll = () => {
ref.current.scrollIntoView({ block: 'end', behavior: 'smooth' })
}
useEffect(() => {
executeScroll()
}, [])
<div className="comment" ref={ref}>
//Data
</div>
I am trying to go to a particular div. I got this error. Any idea why is this error is showing or how to solve it?
"TypeError: Cannot read property 'scrollIntoView' of null"
Upvotes: 0
Views: 515
Reputation: 1680
When the useEffect
runs, the div
hasn't mounted to the DOM yet so the ref
is still null
.
useEffect(() => {
if (ref.current) {
executeScroll();
}
}, [ref.current])
Upvotes: 2