Reputation: 8291
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
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