Skip to content

Instantly share code, notes, and snippets.

@CYBAI CYBAI/LazyLoad.js forked from contra/LazyLoad.js
Last active Nov 12, 2015

Embed
What would you like to do?
lazy loading react components, useful for video/audio/etc
module.exports = (el, distance) => {
if (typeof distance !== 'number') {
distance = 0;
}
let rect = el.getBoundingClientRect();
let paddedRect = {
top: rect.top + distance,
left: rect.left + distance,
right: rect.right - distance,
bottom: rect.bottom - distance
};
let pageHeight = (window.innerHeight || document.documentElement.clientHeight);
let pageWidth = (window.innerWidth || document.documentElement.clientWidth);
let isOnPage = (paddedRect.top >= 0 && paddedRect.left >= 0);
let isUnderPage = (paddedRect.bottom <= pageHeight && paddedRect.right <= pageWidth);
return (isOnPage && isUnderPage);
};
import React from 'react';
import ReactDOM from 'react-dom';
import isVisible from './isVisible';
class LazyLoad extends React.Components {
constructor() {
super();
this.props = {
distance: 100
};
this.state = {
visible: false
};
this._checkViewport = this._checkViewport.bind(this);
}
componentDidMount() {
this._checkViewport();
window.addEventListener('scroll', this._checkViewport);
window.addEventListener('resize', this._checkViewport);
}
componentWillUnmount() {
window.removeEventListener('scroll', this._checkViewport);
window.removeEventListener('resize', this._checkViewport);
}
_checkViewport() {
if (!this.isMounted()) {
return;
}
let el = ReactDOM.findDOMNode(this);
this.setState({
visible: isVisible(el, this.props.distance)
});
}
render() {
// when not visible, return our placeholder
if (!this.state.visible) {
return this.props.component;
}
// otherwise return the children
return this.props.children;
}
}
LazyLoad.propTypes = {
distance: React.PropTypes.number,
component: React.PropTypes.node.isRequired,
children: React.PropTypes.node.isRequired
};
module.exports = LazyLoad;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.