Search code examples
reactjsag-gridag-grid-react

How to add ag-grid react pagination rows per page dropdown


The default AG-Grid does not have a dropdown for pagination. How can I add the pagination drop shown like the image below?

enter image description here


<AgGridReact
  rowData={rowData}
  columnDefs={columnDefs}
  defaultColDef={defaultColDef}
  enableRangeSelection={true}
  rowSelection={'multiple'}
  statusBar={{
    statusPanels:
      [
        { statusPanel: 'agTotalRowCountComponent', align: 'center' },
        { statusPanel: 'agFilteredRowCountComponent' },
        { statusPanel: 'agSelectedRowCountComponent' },
        { statusPanel: 'agAggregationComponent' }
      ]
  }}
  onGridReady={onGridReady}
/>

Solution

  • In the latest version of ag-Grid (version 31), page size selection exists, but ag-Grid does not have a default page size changer (in version 29).

    But it is possible to create such a component. Normally, the page size changer is placed at the bottom of the grid. To achieve this, I typically add a statusPanel to statusPanels of statusBar property.

    I've created the component, and you can see preview at here

    1. Create a PageSize component:
    export interface PaginationProps {
      api: GridApi;
    }
    
    const Pagination: FC<PaginationProps> = ({ api }) => {
      const [pageSize, setPageSize] = useState(api.paginationGetPageSize());
    
      const pageSizes = [1, 5, 10, 20, 50];
    
      const handleChangePageSize = (e) => {
        const value = Number(e.target.value);
        setPageSize(value);
        api.paginationSetPageSize(value);
      };
    
      return (
        <select
          value={pageSize}
          style={{ height: 40, minWidth: 100 }}
          onChange={handleChangePageSize}
        >
          {pageSizes.map((pageSize) => {
            return <option value={pageSize}>{pageSize}</option>;
          })}
        </select>
      );
    };
    
    1. Add Pagination component to components object and statusPanel to statusPanels.

    Please note that the statusPanel property value should match the name of your Pagination component.

    <AgGridReact
      rowData={rowData}
      columnDefs={columnDefs}
      defaultColDef={defaultColDef}
      enableRangeSelection={true}
      rowSelection={"multiple"}
      components={{
        Pagination,
      }}
      statusBar={{
        statusPanels: [
          { statusPanel: "agTotalRowCountComponent", align: "center" },
          { statusPanel: "agFilteredRowCountComponent" },
          { statusPanel: "agSelectedRowCountComponent" },
          { statusPanel: "agAggregationComponent" },
          {
            statusPanel: "Pagination",
            align: "left",
          },
        ],
      }}
      onGridReady={onGridReady}
    />
    

    Finally, I would recommend studying the 'Row Pagination' section of the Ag-Grid documentation at this link.