Created
October 20, 2015 23:07
-
-
Save nkt/abd19ccfa57eff92d0ea to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| const React = require('react'); | |
| const EventListener = require('react/lib/EventListener'); | |
| const {shouldComponentUpdate} = require('react/lib/ReactComponentWithPureRenderMixin'); | |
| const InfinityScroll = React.createClass({ | |
| propTypes: { | |
| children: React.PropTypes.node.isRequired, | |
| enabled: React.PropTypes.bool.isRequired, | |
| threshold: React.PropTypes.number.isRequired, | |
| onScrollDown: React.PropTypes.func.isRequired | |
| }, | |
| getDefaultProps() { | |
| return { | |
| enabled: true, | |
| threshold: 250 | |
| }; | |
| }, | |
| componentDidMount() { | |
| this.listener = EventListener.listen(window, 'scroll', this.onScroll); | |
| this.onScroll(); | |
| }, | |
| shouldComponentUpdate, | |
| componentWillUnmount() { | |
| this.listener.remove(); | |
| }, | |
| onScroll() { | |
| if (!this.props.enabled) { | |
| return; | |
| } | |
| const container = React.findDOMNode(this.refs.container); | |
| const containerTopPosition = this.getElementTopPosition(container); | |
| const scrollTop = this.getScrollTop(); | |
| const bottomDistance = containerTopPosition + container.offsetHeight - scrollTop - window.innerHeight; | |
| if (bottomDistance < this.props.threshold) { | |
| this.props.onScrollDown(); | |
| } | |
| }, | |
| getScrollTop() { | |
| if (window.pageYOffset) { | |
| return window.pageYOffset; | |
| } | |
| return (document.documentElement || document.body.parentNode || document.body).scrollTop; | |
| }, | |
| getElementTopPosition(element) { | |
| if (!element) { | |
| return 0; | |
| } | |
| return element.offsetTop + this.getElementTopPosition(element.offsetParent); | |
| }, | |
| render() { | |
| return ( | |
| <div ref="container"> | |
| {this.props.children} | |
| </div> | |
| ); | |
| } | |
| }); | |
| module.exports = InfinityScroll; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment