-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-index.js
74 lines (60 loc) · 2.24 KB
/
react-index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import React from 'react';
//Simple library to call a function as callback when the scroll bar reaches the bottom of the scroll space of the container
//Input params:
// dropDownContainer: Dom Container that will have a Vertical Scroll Bar
// callback: function that will be called when the scroll bar reaches the bottom of the scrolling space
//Usage:
// <InfinityScrollLoader callback={this.callbackFunction} >
// <DropDownContainer /> //Allows only one child
// </InfinityScrollLoader>
class InfinityScrollLoader extends React.Component {
constructor(props) {
super(props)
this.callback = props.callback
this.lastScrollTop = 0
this.dropDownContainer = this.props.children[0] //Allows only one DropDownContainer to be handled and it has to be the first child.
this.dropDownContainer.scrollTop = 0;
this.pixBeforeBottom = 20
}
shouldLoadNext = (domElements) => {
//If this is a horizontal scroll return false
if (this.lastScrollTop === domElements.scrollTop) { return false }
//Remember last scroll position
this.lastScrollTop = domElements.scrollTop
let scrollHeight = domElements.scrollHeight
let scrollTop = domElements.scrollTop
let clientHeight = domElements.clientHeight
if ((scrollHeight - scrollTop) - this.pixBeforeBottom <= clientHeight) {
return true
} else {
return false
}
}
eventCallBack = (event) => {
if (this.shouldLoadNext(this.dropDownContainer)) {
this.callback()
}
}
addListener = () => {
//Make sure we do not duplicate eventlistener
this.dropDownContainer.removeEventListener('scroll', this.eventCallBack)
this.dropDownContainer.addEventListener('scroll', this.eventCallBack)
}
removeListener = () => {
this.dropDownContainer.removeEventListener('scroll', this.eventCallBack)
}
componentDidMount() {
this.addListener()
}
componentWillUnmount() {
this.removeListener()
}
render() {
return (
<React.Fragment>
{this.props.children[0]}
</React.Fragment>
)
}
}
export default InfinityScrollLoader;