Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component, PropTypes } from 'react';
- export default class LazyTrigger extends Component {
- static propTypes = {
- threshold: PropTypes.number,
- children: PropTypes.any,
- onScreenEnter: PropTypes.func,
- onScreenLeave: PropTypes.func,
- style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
- }
- static defaultProps = {
- threshold: 0,
- }
- constructor(props) {
- super(props);
- this.state = {
- entered: false,
- left: false,
- };
- }
- componentDidMount() {
- window.addEventListener('scroll', ::this.onChange, false);
- window.addEventListener('resize', ::this.onChange, false);
- this.onChange();
- }
- componentWillUnmount() {
- window.removeEventListener('scroll', ::this.onChange, false);
- window.removeEventListener('resize', ::this.onChange, false);
- }
- isInViewport() {
- if (this.trigger) {
- const { threshold } = this.props;
- const { top, left, bottom, right } = element.getBoundingClientRect();
- const width = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
- const height = document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
- const maxWidth = width + threshold;
- const maxHeight = height + threshold;
- return (
- (top >= -threshold && top <= maxHeight || bottom >= -threshold && bottom <= maxHeight) &&
- (left >= -threshold && left <= maxWidth || right >= -threshold && right <= maxWidth)
- );
- }
- return false;
- }
- onChange() {
- if (this.trigger) {
- if (!this.state.entered && isInViewport(this.trigger, this.props.threshold)) {
- this.setState({ entered: true, left: false });
- if (this.props.onScreenEnter) {
- return this.props.onScreenEnter();
- }
- }
- if (!this.state.left && !isInViewport(this.trigger, this.props.threshold)) {
- this.setState({ entered: false, left: true });
- if (this.props.onScreenLeave) {
- return this.props.onScreenLeave();
- }
- }
- }
- return null;
- }
- render() {
- return (
- <div ref={node => (this.trigger = node)} style={this.props.style}>
- {this.props.children}
- </div>
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement