Last active
February 4, 2019 17:33
-
-
Save ShizukuIchi/72463e47aa7a0c78416fa405fcbd15b9 to your computer and use it in GitHub Desktop.
React hook observes intersection of a node.
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 { useState, useEffect } from 'react'; | |
require('intersection-observer'); | |
function useVisibility(ref , ratio = 0.1) { | |
const [visible, setVisible] = useState(false); | |
const callback = entries => { | |
entries.forEach(entry => { | |
setVisible(entry.intersectionRatio >= ratio) | |
}) | |
} | |
useEffect( | |
() => { | |
const options = { | |
threshold: ratio, | |
}; | |
const observer = new IntersectionObserver(callback, options); | |
const target = ref.current | |
if (!target) return; | |
observer.observe(target); | |
return () => { | |
observer.disconnect(); | |
}; | |
}, | |
[ratio], | |
); | |
return visible; | |
} | |
export default useVisibility; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment