[Edit]
+
0
-
0
React - infinite scrolling (custom component)
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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290import React, { useRef, useState, useEffect, useMemo } from 'react'; // Calculates element's absolute position. // const calculateOffset = (element) => { if (element instanceof Window) { return 0; } let result = 0; while (element) { const value = element.offsetTop; if (value) { result += value; } element = element.offsetParent; // jumps to the next proper parent element } return result; }; // Calculates space between elements. // const calculateSpace = (aElement, bElement) => { const aOffset = calculateOffset(aElement); const bOffset = calculateOffset(bElement); return bOffset - aOffset; }; // Calculates container's scroll position. // const calculateScroll = (container) => { return container.scrollY || container.scrollTop || 0; }; // Calculates container's inner height. // const calculateHeight = (container) => { return container.innerHeight || container.clientHeight || 0; }; // Checks barrier visibility inside container. // const checkVisibility = (container, barrier, space) => { const barrierTop = calculateSpace(container, barrier); const containerScroll = calculateScroll(container); const containerHeight = calculateHeight(container); if (barrierTop < containerScroll + containerHeight + space) { return true; } return false; }; // Creates logic that lets to track and control data loading using infinite scolling logic. // const createManager = ({ offset: _offset, space: _space, loader: _loader, container: _container, content: _content, barrier: _barrier, onLoading: _onLoading, onLoaded: _onLoaded, onError: _onError }) => { let _destroyed = false; let _enabled = false; let _loading = false; const signal = () => { if (_loading) { return; } if (_container.current == null || _barrier.current == null || checkVisibility(_container.current, _barrier.current, _space)) { _loading = true; if (_onLoading) { _onLoading(); } const callback = (offset, data, error) => { if (_enabled) { _loading = false; try { if (error) { _onError(error); } else { _offset = offset; if (_onLoaded) { _onLoaded(offset, data); if (_enabled === false) { return; } } if (data && data.length > 0) { setTimeout(signal); } } } catch (e) { console.error(e); } } }; try { _loader(_offset, callback); } catch (e) { _loading = false; if (_onError) { _onError('Loading error.'); } } } }; return { signal: () => { if (_destroyed) { throw new Error('Object has been destroyed.'); } if (_enabled) { signal(); } }, enable: () => { if (_destroyed) { throw new Error('Object has been destroyed.'); } if (_enabled) { return; } _enabled = true; _container.current.addEventListener('scroll', signal, false); signal(); }, disable: () => { if (_destroyed) { throw new Error('Object has been destroyed.'); } if (_enabled) { _enabled = false; _container.current.removeEventListener('scroll', signal, false); } }, destroy: () => { if (_destroyed) { return; } _destroyed = true; _enabled = false; _container.current.removeEventListener('scroll', signal, false); } }; }; // Creates function proxy (Source: https://dirask.com/snippets/jmJNN1). // const createProxy = () => { const state = { wrapper: (...args) => { if (state.action) { return state.action(...args); } return undefined; }, action: null }; return state; }; // Privides proxy hook (Source: https://dirask.com/snippets/jmJNN1). // const useProxy = (action) => { const proxy = useMemo(createProxy, []); proxy.action = action; return proxy.wrapper; }; // Component that implements infinite scolling logic. // const InfinityScrolling = ({ containerRef, pageSize = 20, spaceSize = 100, dataLoader, itemRenderer }) => { const contentRef = useRef(null); const barrierRef = useRef(null); const [offset, setOffset] = useState(0); const [pages, setPages] = useState(null); const [state, setState] = useState(null); const loaderProxy = useProxy(dataLoader); const manager = useMemo( () => { return createManager({ offset: offset, space: spaceSize, loader: loaderProxy, container: containerRef, content: contentRef, barrier: barrierRef, onLoading: () => { setState('Loading...'); }, onLoaded: (offset, items) => { if (items.length > 0) { setOffset(offset); setPages(page => page ? [...page, items] : [items]); } if (items.length < pageSize) { setState(null); manager.disable(); } else { setState('Click me to continue loading...'); } }, onError: (error) => { setState('Loading error! (click me to continue)'); } }); }, [containerRef] ); useEffect( () => { manager.enable(); return () => { manager.disable(); }; }, [containerRef] ); const handleClick = () => manager.signal(); return ( <div className="wrapper"> {pages && ( <div ref={contentRef} className="content"> {pages.map((items, index) => { return ( <div key={index} className="page"> {items.map(itemRenderer)} </div> ); })} </div> )} {state && ( <div ref={barrierRef} className="barrier" onClick={handleClick}> {state} </div> )} </div> ); }; // Usage example: const App = () => { const pageSize = 20; const spaceSize = 300; const containerRef = useRef(window); const loadData = (offset, callback) => { const pageNumber = offset + 1; fetch(`https://randomuser.me/api/?page=${pageNumber}&results=${pageSize}&seed=abc`) .then(response => response.json()) .then(data => callback(pageNumber, data.results, null)) .catch((error) => callback(null, null, 'Loading error!')); }; const renderItem = (item, index) => { const {first, last} = item.name; return ( <div key={index} className="item">{index}. {first} {last}</div> ); }; return ( <div className="app"> <style>{` body { height: 300px } .content { background: #fff6c8 } .barrier { background: #ffc8c8 } `}</style> <InfinityScrolling containerRef={containerRef} pageSize={pageSize} spaceSize={spaceSize} dataLoader={loadData} itemRenderer={renderItem} /> </div> ); }; export default App;
Reset