I'm trying to scroll to an element when it comes into view. The problem is that it only works on a reload when it's already in view.
I've tried debugging it, but the ref seems to be correct and the conditionals pass. There is no return or error message so I don't know how to debug this further.
The hook works as it should so I'm really struggling to figure out what the cause is...
I need to put this in useEffect later on, but even this basic setup doesn't work. Any help is very much appreciated!
EDIT: I need to get this in the center of the screen so that I can overtake the scroll and animate the element on scroll. If I already start that functionality without it being centered, it'll stick to the bottom of the screen while it animates.
const Component = () => {
const sectionRef = useRef<HTMLDivElement>(null);
const isOnScreen = useOnScreen(sectionRef);
if (isOnScreen && sectionRef?.current) {
sectionRef.current.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest'});
}
return (
<section ref={sectionRef}>
// ...child components
</section>
)
}
export default Component
import { useEffect, useState, useRef, RefObject } from 'react';
export default function useOnScreen(ref: RefObject<HTMLElement>) {
const observerRef = useRef<IntersectionObserver | null>(null);
const [isOnScreen, setIsOnScreen] = useState(false);
useEffect(() => {
observerRef.current = new IntersectionObserver(([entry]) =>
setIsOnScreen(entry.isIntersecting)
);
}, []);
useEffect(() => {
if (ref.current) {
observerRef.current?.observe(ref.current);
}
return () => {
observerRef.current?.disconnect();
};
}, [ref]);
return isOnScreen;
}