0

I have the following component definition:

import { useRef } from 'react';

export default function useScroll() {
    const ref = useRef(null)
    const executeScroll = () => {
        if (ref != null)
            window.scrollTo(0, ref.current.offsetTop)
    }
    const htmlElementAttributes = { ref }

    return [executeScroll, htmlElementAttributes]
}

The line window.scrollTo(0, ref.current.offsetTop) throws the error. I have included if (ref != null) check, but did not work. Any ideas?

renakre
  • 8,001
  • 5
  • 46
  • 99

1 Answers1

1

Try ref.current !== null, because:

const ref = useRef(null); // ref is object { current: null }
ref !== null;             // always true
import { useRef } from 'react';

export default function useScroll() {
    const ref = useRef(null)
    const executeScroll = () => {
        if (ref.current !== null)
            window.scrollTo(0, ref.current.offsetTop)
    }
    const htmlElementAttributes = { ref }

    return [executeScroll, htmlElementAttributes]
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118