Datagrid

mail@pastecode.io avatar
unknown
javascript
2 months ago
2.8 kB
2
Indexable
Never
import Pagination from '@mui/material/Pagination';
import PaginationItem from '@mui/material/PaginationItem';
import {Grid, Button, Menu, MenuItem} from '@mui/material';
import * as React from 'react';
import { KeyboardArrowDown } from '@mui/icons-material';

import {
  gridPageCountSelector,
  gridPageSelector,
  gridPageSizeSelector,
  useGridApiContext,
  useGridSelector,
  useGridRootProps,
} from '@mui/x-data-grid';

// Custom Pagination for data table
function CustomPagination() {
  const rootProps = useGridRootProps();
  const apiRef = useGridApiContext();
  const page = useGridSelector(apiRef, gridPageSelector);
  const pageCount = useGridSelector(apiRef, gridPageCountSelector);  
  const pageSizeCount = useGridSelector(apiRef, gridPageSizeSelector);  
  const pageSizeOptions = rootProps.pageSizeOptions  

  // Props For Button Change Page Size Option
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleChangePageSize = (pageSize : number) => {
    apiRef.current.setPageSize(pageSize)

    handleClose()
  }

  

  return (
  <Grid
    container
    direction="row"
    justifyContent="space-between"
    alignItems="center"
  >
      {/* Page Size Option Button Menu */}
      <Grid item xs={6} sx={{p: 2}}>   
        <Button
          id="pagination-button"
          color="primary"
          size="small"
          variant="contained"
          aria-controls={open ? 'basic-menu' : undefined}
          aria-haspopup="true"
          aria-expanded={open ? 'true' : undefined}
          onClick={handleClick}
          endIcon={<KeyboardArrowDown />}

        >
          {pageSizeCount}
        </Button>
        <Menu
          id="pagination-menu"
          anchorEl={anchorEl}
          open={open}
          onClose={handleClose}
          MenuListProps={{
            'aria-labelledby': 'pagination-button',
          }}
        >
          {pageSizeOptions.map((opt : number) => {
            return(
              <MenuItem onClick={ () => {handleChangePageSize(opt)}}>{opt}</MenuItem>
            )
          })}
          
        </Menu>
      </Grid>
      {/* Pagination Button */}
      <Pagination
        color="primary"
        // variant="outlined"
        shape="rounded"
        page={page + 1}
        count={pageCount}
        // @ts-expect-error
        renderItem={(props2) => <PaginationItem {...props2} disableRipple />}
        onChange={(event: React.ChangeEvent<unknown>, value: number) =>
          apiRef.current.setPage(value - 1)
        }
      />
  </Grid>
  );
}

export default CustomPagination;
Leave a Comment