The pagination with Grid.js in React is typically achieved by setting the server property to true and using a handler function to manage the page size and current page.
Let's assume that your server accepts limit and offset query parameters for pagination and that you have an API endpoint called /api/data.
Firstly, make sure you have installed the gridjs and gridjs-react packages:
npm[ or yarn] install gridjs gridjs-react
Then, here is an example of how you can mostly implement this in your React component but do remember there will be some adding to this depending on your application requirements:
import { Grid, GridRow } from "gridjs-react";
const MyTable = () => {
const [totalPages, setTotalPages] = useState(0);
const gridInstance = new gridjs.Grid({
server: {
url: '/api/data',
method: 'GET',
// beforeRequest hook allows you to manipulate the request parameters
beforeRequest: (params) => {
return {
...params,
limit: params.limit,
offset: params.offset,
};
},
// afterRequest hook allows you to manipulate the response
afterRequest: (data) => {
setTotalPages(Math.ceil(data.total / data.limit));
return data;
},
then: data => ({
data: data.items,
total: data.total,
}),
handle: (res) => {
if (res.ok) {
return res.json();
}
throw Error("Network error");
},
},
pagination: {
enabled: true,
limit: 10,
summary: (_, total) => `Showing ${total} entries`,
},
}).render();
return (
<div>
<GridRow>
<p>
Showing 1 to 10 of {totalPages} entries
Prev. 1 2 3 4 5 … 100 Next
</p>
</GridRow>
{gridInstance}
</div>
);
}
export default MyTable;
The beforeRequest hook in server allows us to modify the request parameters. So, in this case, we use the limit and offset values from the Grid.js request and send them to our server.
The afterRequest hook is used to get the total number of pages and set it to the state. Note that in this example, we assume that the server responds with the total number of items (total) and the items for the current page (items).
Lastly, we use the pagination option to enable pagination and set the page size to 10. We customise the pagination summary text by providing a function to summary. This function receives the current page's data and the total number of data, and returns a string that will be displayed in the pagination summary.
Note: If you want to show the custom pagination (like Prev. 1 2 3 4 5 … 100 Next), you might have to create your own custom pagination component. Grid.js doesn't provide a built-in way to customise the appearance of the pagination controls beyond the summary.