Skip to content

Instantly share code, notes, and snippets.

@danielberndt
Created January 7, 2019 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielberndt/f09f92c1120f75c2094df18fee9045b9 to your computer and use it in GitHub Desktop.
Save danielberndt/f09f92c1120f75c2094df18fee9045b9 to your computer and use it in GitHub Desktop.
IsIntersecting Component using IntersectionObserver
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