Coding exercise: implement pagination in React.

React practical coding · Freshers

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

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