Blog>
Snippets

Implementing Pagination with TanStack Ranger

Show how to add pagination to a data table using TanStack Ranger, covering the setup of pagination controls and integrating them with your data set.
// Define the state for pagination
const [pageIndex, setPageIndex] = React.useState(0);
const [pageSize, setPageSize] = React.useState(10);
This code snippet defines the state for pagination including the current page index and page size.
// Define a function to fetch your data (simulated here with setTimeout)
// This function would typically fetch data based on the current page/size
function fetchData({ pageIndex, pageSize }) {
  return new Promise(resolve => {
    setTimeout(() => {
      const startRow = pageIndex * pageSize;
      const data = [];
      // Populate your data array here based on startRow and pageSize
      resolve({ data, pageIndex, pageSize });
    }, 1000); // Simulated network request time
  });
}
Defines a mock function to simulate fetching data from an API based on the pagination state. In a real scenario, this function would fetch the data from your backend service.
// React effect hook to load data on component mount and when pagination state changes
React.useEffect(() => {
  fetchData({ pageIndex, pageSize }).then(result => {
    // Process your data here
    console.log('Data fetched for page:', pageIndex, 'with size:', pageSize, result.data);
  });
}, [pageIndex, pageSize]);
Uses React's useEffect hook to call the fetchData function whenever the pagination state changes, i.e., when pageIndex or pageSize is updated.
// Pagination controls
return (
  <div>
    <button onClick={() => setPageIndex(pageIndex - 1)} disabled={pageIndex === 0}>Previous</button>
    <button onClick={() => setPageIndex(pageIndex + 1)}>Next</button>
    <div>Current Page: {pageIndex + 1}</div>
  </div>
);
Renders simple previous and next buttons to control pagination and displays the current page. Adjusts the pageIndex state on button clicks.