renakre
renakre

Reputation: 8291

Object is possibly 'null'. TS2531 Error when defining useScroll hook

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?

Upvotes: 0

Views: 358

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53894

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]
}

Upvotes: 1

Related Questions