Created
October 18, 2023 14:07
-
-
Save chrisciampoli/bd1f846217172cbea7ea12252f8a8afe to your computer and use it in GitHub Desktop.
useObserver Custom React Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { useIntersectionObserver } from './useIntersectionObserver'; // Import your custom hook | |
function MyComponent() { | |
const { observedRef, inView } = useIntersectionObserver(); | |
return ( | |
<div | |
className={`flex-1 parent-flex flex ${inView ? 'group inview' : ''}`} | |
ref={observedRef} | |
> | |
{/* Your component content */} | |
</div> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client'; | |
import { ReactNode, useEffect, useRef, useState } from 'react'; | |
export default function Observer({ | |
children, | |
className, | |
key, | |
repeat = false, | |
}: { | |
children: ReactNode; | |
className?: string; | |
key?: string; | |
repeat?: boolean; | |
}) { | |
const [inView, setInView] = useState<boolean>(false); | |
const observed = useRef(null); | |
const [once, setOnce] = useState<boolean>(false); | |
useEffect(() => { | |
const reff = observed; | |
const observer = new IntersectionObserver( | |
(e) => { | |
if (observed.current) { | |
setInView(() => e[0].isIntersecting); | |
if (e[0].isIntersecting) { | |
setOnce(() => true); | |
} | |
} | |
}, | |
{ threshold: 0.6 } | |
); | |
if (reff.current) { | |
observer.observe(reff.current); | |
} | |
return () => { | |
if (reff.current) { | |
observer.unobserve(reff.current); | |
} | |
}; | |
}, []); | |
return ( | |
<div | |
key={key} | |
className={`flex-1 parent-flex flex ${className ? className : ''} ${ | |
inView || (once && !repeat) ? 'group inview' : '' | |
}`} | |
ref={observed} | |
> | |
{children} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment