Skip to content

Commit 6386fe4

Browse files
committed
Support threshold with units. e.g 100px, 80%...
1 parent c7da363 commit 6386fe4

File tree

2 files changed

+54
-3
lines changed

2 files changed

+54
-3
lines changed

app/index.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React, { Component } from "react";
22
import PropTypes from "prop-types";
3-
import throttle from './utils/throttle';
3+
import throttle from "./utils/throttle";
4+
import { ThresholdUnits, parseThreshold } from "./utils/threshold";
45

56
export default class InfiniteScroll extends Component {
67
constructor(props) {
@@ -161,8 +162,16 @@ export default class InfiniteScroll extends Component {
161162
? window.screen.availHeight
162163
: target.clientHeight;
163164

165+
const threshold = parseThreshold(scrollThreshold);
166+
167+
if (threshold.unit === ThresholdUnits.Pixel) {
168+
return (
169+
target.scrollTop + clientHeight >= target.scrollHeight - threshold.value
170+
);
171+
}
172+
164173
return (
165-
target.scrollTop + clientHeight >= scrollThreshold * target.scrollHeight
174+
target.scrollTop + clientHeight >= threshold.value / 100 * target.scrollHeight
166175
);
167176
}
168177

@@ -263,7 +272,7 @@ InfiniteScroll.propTypes = {
263272
hasMore: PropTypes.bool,
264273
children: PropTypes.node,
265274
loader: PropTypes.node.isRequired,
266-
scrollThreshold: PropTypes.number,
275+
scrollThreshold: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
267276
endMessage: PropTypes.node,
268277
style: PropTypes.object,
269278
height: PropTypes.number,

app/utils/threshold.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
export const ThresholdUnits = {
2+
Pixel: 'Pixel',
3+
Percent: 'Percent',
4+
};
5+
6+
const defaultThreshold = {
7+
unit: ThresholdUnits.Percent,
8+
value: 0.8,
9+
};
10+
11+
export function parseThreshold(scrollThreshold) {
12+
if (typeof scrollThreshold === "number") {
13+
return {
14+
unit: ThresholdUnits.Percent,
15+
value: scrollThreshold * 100,
16+
};
17+
}
18+
19+
if (typeof scrollThreshold === "string") {
20+
if (scrollThreshold.match(/^(\d*(.\d+)?)px$/)) {
21+
return {
22+
unit: ThresholdUnits.Pixel,
23+
value: parseFloat(scrollThreshold),
24+
};
25+
}
26+
27+
if (scrollThreshold.match(/^(\d*(.\d+)?)%$/)) {
28+
return {
29+
unit: ThresholdUnits.Percent,
30+
value: parseFloat(scrollThreshold),
31+
};
32+
}
33+
34+
console.warn('scrollThreshold format is invalid. Valid formats: "120px", "50%"...');
35+
36+
return defaultThreshold;
37+
}
38+
39+
console.warn('scrollThreshold should be string or number');
40+
41+
return defaultThreshold;
42+
}

0 commit comments

Comments
 (0)