Created
January 30, 2018 00:27
-
-
Save tuxsudo/0a4f5d3db4bf45d6324ebc4c59711ab7 to your computer and use it in GitHub Desktop.
React Intersection Observer
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 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 }); | |
} | |
} |
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 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