Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. import React, { Component, PropTypes } from 'react';
  2.  
  3. export default class LazyTrigger extends Component {
  4. static propTypes = {
  5. threshold: PropTypes.number,
  6. children: PropTypes.any,
  7. onScreenEnter: PropTypes.func,
  8. onScreenLeave: PropTypes.func,
  9. style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  10. }
  11.  
  12. static defaultProps = {
  13. threshold: 0,
  14. }
  15.  
  16. constructor(props) {
  17. super(props);
  18. this.state = {
  19. entered: false,
  20. left: false,
  21. };
  22. }
  23.  
  24. componentDidMount() {
  25. window.addEventListener('scroll', ::this.onChange, false);
  26. window.addEventListener('resize', ::this.onChange, false);
  27. this.onChange();
  28. }
  29.  
  30. componentWillUnmount() {
  31. window.removeEventListener('scroll', ::this.onChange, false);
  32. window.removeEventListener('resize', ::this.onChange, false);
  33. }
  34.  
  35. isInViewport() {
  36. if (this.trigger) {
  37. const { threshold } = this.props;
  38. const { top, left, bottom, right } = element.getBoundingClientRect();
  39. const width = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
  40. const height = document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
  41. const maxWidth = width + threshold;
  42. const maxHeight = height + threshold;
  43.  
  44. return (
  45. (top >= -threshold && top <= maxHeight || bottom >= -threshold && bottom <= maxHeight) &&
  46. (left >= -threshold && left <= maxWidth || right >= -threshold && right <= maxWidth)
  47. );
  48. }
  49.  
  50. return false;
  51. }
  52.  
  53. onChange() {
  54. if (this.trigger) {
  55. if (!this.state.entered && isInViewport(this.trigger, this.props.threshold)) {
  56. this.setState({ entered: true, left: false });
  57.  
  58. if (this.props.onScreenEnter) {
  59. return this.props.onScreenEnter();
  60. }
  61. }
  62.  
  63. if (!this.state.left && !isInViewport(this.trigger, this.props.threshold)) {
  64. this.setState({ entered: false, left: true });
  65.  
  66. if (this.props.onScreenLeave) {
  67. return this.props.onScreenLeave();
  68. }
  69. }
  70. }
  71.  
  72. return null;
  73. }
  74.  
  75. render() {
  76. return (
  77. <div ref={node => (this.trigger = node)} style={this.props.style}>
  78. {this.props.children}
  79. </div>
  80. );
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement