Intersection Observer in React
Hi! I'm trying to write a custom hook to get an intersection observer in react. I've been getting this error : I can't seem to understand what's causing this.
Code:
Appreciate any suggestions. Thanks!
Type 'boolean | MutableRefObject<HTMLElement | null>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
Type 'false' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.Type 'boolean | MutableRefObject<HTMLElement | null>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
Type 'false' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.Code:
import { useRef, useState, useEffect } from "react";
type Props = {
options?: {
root: null;
rootMargin: string;
threshold: number;
};
};
export function useIntersectionObserver({
options = {
root: null,
rootMargin: "-100px",
threshold: 0,
},
}: Props) {
const ref = useRef<HTMLElement | null>(null);
const [visible, setVisible] = useState<boolean>(false);
useEffect(() => {
const observer = new IntersectionObserver((entries, observer) => {
const [entry] = entries;
setVisible(entry.isIntersecting);
}, options);
if (ref.current) observer.observe(ref?.current);
const current = ref?.current;
return () => {
if (current) observer.unobserve(current);
};
}, [ref, options]);
return [ref, visible];
}import { useRef, useState, useEffect } from "react";
type Props = {
options?: {
root: null;
rootMargin: string;
threshold: number;
};
};
export function useIntersectionObserver({
options = {
root: null,
rootMargin: "-100px",
threshold: 0,
},
}: Props) {
const ref = useRef<HTMLElement | null>(null);
const [visible, setVisible] = useState<boolean>(false);
useEffect(() => {
const observer = new IntersectionObserver((entries, observer) => {
const [entry] = entries;
setVisible(entry.isIntersecting);
}, options);
if (ref.current) observer.observe(ref?.current);
const current = ref?.current;
return () => {
if (current) observer.unobserve(current);
};
}, [ref, options]);
return [ref, visible];
}Appreciate any suggestions. Thanks!
