Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
lazy loading react components, useful for video/audio/etc
module.exports = function(el, distance) {
if (typeof distance !== 'number') {
distance = 0;
}
// TODO: use distance to create alternate bounding client rect
var rect = el.getBoundingClientRect();
var paddedRect = {
top: rect.top + distance,
left: rect.left + distance,
right: rect.right - distance,
bottom: rect.bottom - distance
};
var pageHeight = (window.innerHeight || document.documentElement.clientHeight);
var pageWidth = (window.innerWidth || document.documentElement.clientWidth);
var isOnPage = (paddedRect.top >= 0 && paddedRect.left >= 0);
var isUnderPage = (paddedRect.bottom <= pageHeight && paddedRect.right <= pageWidth);
return (isOnPage && isUnderPage);
};
var React = require('react');
var events = require('add-event-listener');
var isVisible = require('../isVisible');
var LazyLoad = React.createClass({
displayName: 'LazyLoad',
propTypes: {
distance: React.PropTypes.number,
component: React.PropTypes.node.isRequired,
children: React.PropTypes.node.isRequired
},
getDefaultProps: function() {
return {
distance: 100
};
},
getInitialState: function() {
return {
visible: false
};
},
componentDidMount: function() {
this._checkViewport();
events.addEventListener(window, 'scroll', this._checkViewport);
events.addEventListener(window, 'resize', this._checkViewport);
},
componentWillUnmount: function() {
events.removeEventListener(window, 'scroll', this._checkViewport);
events.removeEventListener(window, 'resize', this._checkViewport);
},
_checkViewport: function() {
if (!this.isMounted()) {
return;
}
var el = this.getDOMNode();
this.setState({
visible: isVisible(el, this.props.distance)
});
},
render: function() {
// when not visible, return our placeholder
if (!this.state.visible) {
return this.props.component;
}
// otherwise return the children
return this.props.children;
}
});
module.exports = LazyLoad;
@waleedarshad-vf

This comment has been minimized.

Copy link

@waleedarshad-vf waleedarshad-vf commented Aug 24, 2016

Will it work for react native???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment