javascript / intermediate
Snippet
Matrix Grid Transformation using Array Slice Pagination in React
Transforming flat lists into multi-dimensional matrix rows for windowed or chunked rendering in React is accomplished cleanly with nested `Array.prototype.slice` operations. By isolating the computation inside `useMemo`, array slicing and chunk allocations execute only when pagination bounds change.
snippet.js
javascript
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
import { useMemo } from 'react';export function PaginatedDataGrid({ items, columnsPerRow = 3, currentPage = 0, pageSize = 6 }) {const paginatedRows = useMemo(() => {const startIdx = currentPage * pageSize;const activeSlice = items.slice(startIdx, startIdx + pageSize);const rows = [];for (let i = 0; i < activeSlice.length; i += columnsPerRow) {rows.push(activeSlice.slice(i, i + columnsPerRow));}return rows;}, [items, columnsPerRow, currentPage, pageSize]);return (<div className="grid-container">{paginatedRows.map((row, rowIndex) => (<div key={`row-${rowIndex}`} className="grid-row">{row.map((cell) => (<span key={cell.id} className="grid-cell">{cell.label}</span>))}</div>))}</div>);}
react
Breakdown
1
const activeSlice = items.slice(startIdx, startIdx + pageSize);
Extracts a shallow copy subset representing the items belonging to the current page view.
2
for (let i = 0; i < activeSlice.length; i += columnsPerRow) {
Iterates in stepped increments equal to column capacity to organize items into rows.
3
rows.push(activeSlice.slice(i, i + columnsPerRow));
Slices each chunk out of the page dataset and stores it as a sub-array row.