Created
June 13, 2020 07:48
-
-
Save LishuGupta652/b2a3ebd41b3ce32a6ae4a952e050b9d3 to your computer and use it in GitHub Desktop.
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, { useEffect, useState } from "react"; | |
import { useIntersection } from "react-use"; | |
export const IntersectionContext = React.createContext({ inView: true }); | |
export const IntersectionObserver = ({ | |
children, | |
reset = false // if value set to true - observed element will reappear every time it shows up on the screen | |
}) => { | |
const [inView, setInView] = useState(false); | |
const intersectionRef = React.useRef(null); | |
const intersection = useIntersection(intersectionRef, { | |
threshold: 0 | |
}); | |
useEffect(() => { | |
const inViewNow = intersection && intersection.intersectionRatio > 0; | |
if (inViewNow) { | |
return setInView(inViewNow); | |
} else if (reset) { | |
return setInView(false); | |
} | |
}, [intersection, reset]); | |
return ( | |
<IntersectionContext.Provider value={{ inView }}> | |
<div ref={intersectionRef}>{children}</div> | |
</IntersectionContext.Provider> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment