This repository has been archived by the owner on Dec 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathexample.js
109 lines (96 loc) · 2.65 KB
/
example.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
// LazyList wraps around ReactList--so we need both!
import LazyList from 'react-list-lazy-load'
import ReactList from 'react-list'
const randBetween = (min, max) =>
Math.floor(min + (Math.random() * (max - min)))
// Utility to create arrays with test data
const array = (len, val = () => null) => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(val(i))
}
return arr
}
function mergePage (items, newItems, offset) {
const merged = items.slice()
newItems.forEach((item, idx) => {
merged[idx + offset] = item
})
return merged
}
class App extends React.Component {
constructor (props) {
super(props)
this.state = {
items: array(25, (i) => `item #${i}`)
}
this.handleRequestPage = this.handleRequestPage.bind(this)
}
// Simulate a network request for `limit` items
fetch (page, cb) {
const { minLoadTime, maxLoadTime, pageSize } = this.props
setTimeout(() => {
// Generate a new page of items
const data = array(pageSize, (i) => `item #${(page * pageSize) + i}`)
cb(data)
}, randBetween(minLoadTime, maxLoadTime))
}
handleRequestPage (page, cb) {
const { pageSize } = this.props
// Simulate a network request or other async operation
this.fetch(page, (data) => {
// Merge the new page into the current `items` collection and rerender
this.setState({
items: mergePage(this.state.items, data, page * pageSize)
})
// Tell LazyList that the page was loaded
cb()
})
}
render () {
const { totalItems } = this.props
const { items } = this.state
return (
<LazyList
pageSize={this.props.pageSize}
items={items}
length={totalItems}
onRequestPage={this.handleRequestPage}
>
<ReactList
type='uniform'
length={totalItems}
itemRenderer={(index, key) => (
// If `items[index] == null`, the page is still being loaded.
items[index] != null ? (
<div key={key}>
#{index}
<strong>{items[index]}</strong>
</div>
) : (
<div key={key}>Loading …</div>
)
)}
/>
</LazyList>
)
}
}
App.propTypes = {
pageSize: PropTypes.number.isRequired,
totalItems: PropTypes.number.isRequired,
minLoadTime: PropTypes.number.isRequired,
maxLoadTime: PropTypes.number.isRequired
}
ReactDOM.render(
<App
pageSize={10}
totalItems={1000}
minLoadTime={250}
maxLoadTime={1250}
/>,
document.getElementById('example')
)