Skip to content

Instantly share code, notes, and snippets.

@danielberndt
Created January 7, 2019 11:20
Show Gist options
  • Save danielberndt/f09f92c1120f75c2094df18fee9045b9 to your computer and use it in GitHub Desktop.
Save danielberndt/f09f92c1120f75c2094df18fee9045b9 to your computer and use it in GitHub Desktop.

Revisions

  1. danielberndt created this gist Jan 7, 2019.
    45 changes: 45 additions & 0 deletions IsIntersecting.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    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});
    }
    }