Created
September 3, 2019 00:23
-
-
Save kilgarenone/e42accd6c766ec5e068dc1165468fe9a to your computer and use it in GitHub Desktop.
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 { h, Component } from "preact"; | |
class Observer extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { isVisible: false }; | |
this.io = null; | |
this.container = null; | |
} | |
componentDidMount() { | |
// polyfill IntersectionObserver on-demand! | |
(window.IntersectionObserver ? Promise.resolve() : import("intersection-observer")).then(() => { | |
this.io = new window.IntersectionObserver( | |
entries => { | |
entries.forEach(entry => { | |
this.setState({ isVisible: entry.isIntersecting }); | |
}); | |
}, | |
{ root: null, rootMargin: "100px", threshold: 0.5 } // adjust accordingly (https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver#Properties) | |
); | |
this.io.observe(this.container); | |
}); | |
} | |
componentWillUnmount() { | |
if (this.io) { | |
this.io.disconnect(); | |
} | |
} | |
render() { | |
return ( | |
<div | |
ref={div => { | |
this.container = div; | |
}} | |
> | |
{Array.isArray(this.props.children) | |
? this.props.children.map(child => child(this.state.isVisible)) | |
: this.props.children(this.state.isVisible)} // calling the child function | |
</div> | |
); | |
} | |
} | |
export default Observer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment