Coding exercise: implement pagination in React.
Model answer
For a small list, slice the array. Keep the page number in state and work out the page count. For a large dataset, ask the server for one page at a time (page and limit) instead.
function PagedList({ items, pageSize = 5 }) {
const [page, setPage] = useState(1);
const pages = Math.max(1, Math.ceil(items.length / pageSize));
const current = Math.min(page, pages);
const slice = items.slice((current - 1) * pageSize, current * pageSize);
return (
<>
<ul>{slice.map((x) => <li key={x.id}>{x.name}</li>)}</ul>
<button disabled={current === 1} onClick={() => setPage(current - 1)}>Previous</button>
<span> Page {current} of {pages} </span>
<button disabled={current === pages} onClick={() => setPage(current + 1)}>Next</button>
</>
);
}For server pagination, put the page in the fetch effect's dependency list and keep the old rows on screen while the next page loads.
Tips
- Handle the edge cases: empty list, and the page number after items are deleted.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.
- Coding exercise: implement sorting and filtering in React.