Skip to content

Instantly share code, notes, and snippets.

@tuxsudo
Created January 30, 2018 00:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxsudo/0a4f5d3db4bf45d6324ebc4c59711ab7 to your computer and use it in GitHub Desktop.
Save tuxsudo/0a4f5d3db4bf45d6324ebc4c59711ab7 to your computer and use it in GitHub Desktop.
React Intersection Observer
import React from "react";
export default class IntersectionObserver extends React.Component {
static defaultProps = {
root: null,
rootMargin: undefined,
threshold: 0,
onChange: () => null,
render: () => null
};
state = {
entry: {}
};
observer = null;
componentDidMount() {
const { root, rootMargin, threshold } = this.props;
if (window && window.IntersectionObserver) {
this.observer = new window.IntersectionObserver(this.handleIntersect, {
root,
rootMargin,
threshold
});
this.observer.observe(this.node);
}
}
componentWillUnmount() {
this.observer.disconnect();
}
handleIntersect = ([entry]) => {
const { onChange } = this.props;
this.setState({ entry });
onChange(entry);
};
handleRef = node => (this.node = node);
render() {
const { render } = this.props;
const { entry } = this.state;
return render({ refHandler: this.handleRef, entry });
}
}
import IntersectionObserver from "./IntersectionObserver";
() =>
<Intersection
render={({ refHandler, entry }) => (
<div ref={refHandler}>
{entry.isIntersecting ? "i'm in view" : "you can't see me"}
</div>
)}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment