Created
January 7, 2019 11:20
-
-
Save danielberndt/f09f92c1120f75c2094df18fee9045b9 to your computer and use it in GitHub Desktop.
IsIntersecting Component using IntersectionObserver
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"; | |
export default class IsIntersecting extends React.Component { | |
state = {isIntersecting: false}; | |
observer = null; | |
rootRef = React.createRef(); | |
elementRef = React.createRef(); | |
componentDidMount() { | |
this.checkIfSetup(); | |
} | |
componentDidUpdate() { | |
this.checkIfSetup(); | |
} | |
checkIfSetup() { | |
if (typeof IntersectionObserver === "undefined") return; | |
if (!this.observer) { | |
if (this.rootRef.current && this.elementRef.current) { | |
this.observer = new IntersectionObserver(this.onUpdate, { | |
root: this.rootRef.current, | |
threshold: [0, 0.001], | |
}); | |
this.observer.observe(this.elementRef.current); | |
} | |
} else { | |
if (!this.rootRef.current || !this.elementRef.current) { | |
console.log("teardown"); | |
this.observer.disconnect(); | |
this.observer = null; | |
} | |
} | |
} | |
onUpdate = entries => { | |
console.log("entries", entries); | |
}; | |
render() { | |
const {isActive} = this.state; | |
return this.props.children({rootRef: this.rootRef, elementRef: this.elementRef, isActive}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment