Shahariar Rahman Sajib
Shahariar Rahman Sajib

Reputation: 157

TypeError: Cannot read property 'scrollIntoView' of null How to solve?

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

Answers (1)

LMulvey
LMulvey

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

Related Questions