Infinite Scroll
Description
Demo
Infinite Scroll with JSON data
const Example: React.FC = () => {
const [dataset, setDataset] = useState<any[]>([]);
const [columns, setColumns] = useState<Column[]>([]);
const [options, setOptions] = useState<GridOption | undefined>(undefined);
const reactGridRef = useRef<SlickgridReactInstance | null>(null);
useEffect(() => defineGrid());
function reactGridReady(reactGrid: SlickgridReactInstance) {
reactGridRef.current = reactGrid;
}
// add onScroll listener which will detect when we reach the scroll end
// if so, then append items to the dataset
function handleOnScroll(event) {
const args = event.detail?.args;
const viewportElm = args.grid.getViewportNode();
if (
['mousewheel', 'scroll'].includes(args.triggeredBy || '')
&& !scrollEndCalled
&& viewportElm.scrollTop > 0
&& Math.ceil(viewportElm.offsetHeight + args.scrollTop) >= args.scrollHeight
) {
// onScroll end reached, add more items
// for demo purposes, we'll mock next subset of data at last id index + 1
const startIdx = reactGridRef.current?.dataView?.getItemCount() || 0;
const newItems = loadData(startIdx, FETCH_SIZE);
reactGridRef.current?.dataView?.addItems(newItems);
scrollEndCalled = false; //
}
}
// do we want to reset the dataset when Sorting?
// if answering Yes then use the code below
function handleOnSort() {
if (shouldResetOnSort) {
const newData = loadData(0, FETCH_SIZE);
reactGridRef.current?.slickGrid?.scrollTo(0); // scroll back to top to avoid unwanted onScroll end triggered
reactGridRef.current?.dataView?.setItems(newData);
reactGridRef.current?.dataView?.reSort();
}
}
return !options ? null : (
<SlickgridReact gridId="grid1"
columns={columns}
options={options}
dataset={dataset}
onReactGridCreated={$event => reactGridReady($event.detail)}
onScroll={$event => handleOnScroll($event.$detail.args)}
onSort={$event => handleOnSort())}
/>
);
}Infinite Scroll with Backend Services
Last updated