Flavio Rocha 2018
Flavio Rocha 2018

Reputation: 47

How to change styles in Table Pagination Material-ui v.5.0 with React

I'm trying to change the width, height and color of table pagination on Material-ui V5.0 with React, but it does not accept classes. As the pagination uses .MuiToolbar-root, if I make changes with a .css file, it brakes my MuiToolbar at the top of the App page. How should I apply the changes needed without braking the Appbar at the top? Also, I will need to change the padding of .MuiTableCell-root as well. I'm sending my code bellow. Please all helps will be very appreciated.

// Component SupplierTable

import React, {useState} from 'react'
import './SupplierTable.css';
import SupplierForm from './SupplierForm';
import PageHeader from '../components/PageHeader';
import FactoryIcon from '@mui/icons-material/Factory';
import * as supplierService from '../services/EmployeeService';
import Controls from "../components/controls/Controls";
import { InputAdornment } from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import AddIcon from '@mui/icons-material/Add';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import useTable from "../components/useTable";
import { makeStyles } from '@mui/styles';
import ModeEditOutlineIcon from '@mui/icons-material/ModeEditOutline';
import { TableRow, TableBody, TableCell } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import Popup from '../components/Poup';
import Notification from '../components/Notifications';
import ConfirmDialog from '../components/ConfirmDialog';
import Grid from '@mui/material/Grid';

const useStyles = makeStyles(theme => ({
    overrides: {
        '&.MuiTablePagination-root':{
            width: '960px',
            height: '35px',
            backgroundColor: '#a9aeb3',
            color: 'rgb(41, 39, 39)',
            fontFamily: 'Arial, Helvetica, sansSerif',
            fontWeight: '700',
        }
    },

  pageContent: {
    margin: theme.spacing(1),
    padding: theme.spacing(3)
},
  searchInput: {
    width: '50%'
},
  newButton: {
    position: 'absolute',
    right: '0px'
},
  
}));


const headCells = [
  { id: 'fullName', label: 'Employee Name' },
  { id: 'email', label: 'Email Address (Personal)' },
  { id: 'mobile', label: 'Mobile Number' },
  { id: 'department', label: 'Department' },
  { id: 'actions', label: 'Actions', disableSorting: true }
]

export default function Supplyer() {
  const classes = useStyles();
  const [recordForEdit, setRecordForEdit] = useState(null)
  const [records, setRecords] = useState(supplierService.getAllSuppliers())
  const [filterFn, setFilterFn] = useState({ fn: items => { return items; } })
  const [openPopup, setOpenPopup] = useState(false)
  const [notify, setNotify] = useState({ isOpen: false, message: '', type: '' })
  const [confirmDialog, setConfirmDialog] = useState({ isOpen: false, title: '', subTitle: '' })

  const {
      TblContainer,
      TblHead,
      TblPagination,
      recordsAfterPagingAndSorting
  } = useTable(records, headCells, filterFn);

  const handleSearch = e => {
    let target = e.target;
    setFilterFn({
        fn: items => {
            if (target.value == "")
                return items;
            else
                return items.filter(x => x.fullName.toLowerCase().includes(target.value))
        }
    })
}

const addOrEdit = (employee, resetForm) => {
  if (employee.id == 0)
  supplierService.insertEmployee(employee)
  else
  supplierService.updateEmployee(employee)
  resetForm()
  setRecordForEdit(null)
  setOpenPopup(false)
  setRecords(supplierService.getAllEmployees())
  setNotify({
      isOpen: true,
      message: 'Submitted Successfully',
      type: 'success'
  })
}

const openInPopup = item => {
  setRecordForEdit(item)
  setOpenPopup(true)
}

const onDelete = id => {
  setConfirmDialog({
      ...confirmDialog,
      isOpen: false
  })
  supplierService.deleteEmployee(id);
  setRecords(supplierService.getAllEmployees())
  setNotify({
      isOpen: true,
      message: 'Deleted Successfully',
      type: 'error'
  })
}
  return (
    <>
        
        <PageHeader
        title= "Fornecedores"
        subTitle="Tabela de Fornecedores - Novo / Atualizar"
        icon={<FactoryIcon fontSize="large" text-align='center'/>}
        />
        
        <Box sx={{width: "1060px"}}>
        <Paper className={classes.pageContent}>
        <Grid container direction= 'row' justifyContent="space-between" >
        <Controls.Input 
                        label="Pesquisar Fornecedor"
                        className={classes.searchInput}
                        InputProps={{
                            startAdornment: (<InputAdornment position="start">
                                <SearchIcon />
                            </InputAdornment>)
                        }}
                        onChange={handleSearch}
                    />
                   
                    <Controls.Button 
                        text="Adicionar"
                        variant="outlined"
                        color="primary"
                        startIcon={<AddIcon />}
                        className={classes.newButton}
                        onClick={() => { setOpenPopup(true); setRecordForEdit(null); }}
                    />
                   
                    </Grid>
                     <TblContainer>
                    <TblHead />
                    <TableBody>
                        {
                            recordsAfterPagingAndSorting().map(item =>
                                (<TableRow key={item.id}>
                                    <TableCell>{item.fullName}</TableCell>
                                    <TableCell>{item.email}</TableCell>
                                    <TableCell>{item.mobile}</TableCell>
                                    <TableCell>{item.department}</TableCell>
                                    <TableCell>
                                        <Controls.ActionButton
                                            color="primary"
                                            onClick={() => { openInPopup(item) }}>
                                            <ModeEditOutlineIcon fontSize="small" />
                                        </Controls.ActionButton>
                                        <Controls.ActionButton
                                            color="secondary"
                                            onClick={() => {
                                                setConfirmDialog({
                                                    isOpen: true,
                                                    title: 'Are you sure to delete this record?',
                                                    subTitle: "You can't undo this operation",
                                                    onConfirm: () => { onDelete(item.id) }
                                                })
                                            }}>
                                            <CloseIcon fontSize="small" />
                                        </Controls.ActionButton>
                                    </TableCell>
                                </TableRow>)
                            )
                        }
                    </TableBody>
                </TblContainer> 
        **strong text**  // Pagination begins here!!!!!
                <TblPagination components={{
                    Toolbar: props => (
                        <div>
                        style={{ backgroundColor: '#a9aeb3', width: '950px',  color: 'rgb(41, 39, 39)',
                                height: '35px' }}
                        </div>
                    )
                }}/>
            </Paper>
            </Box>
            <Popup
                title="Employee Form"
                openPopup={openPopup}
                setOpenPopup={setOpenPopup}
            >
                <SupplierForm
                    recordForEdit={recordForEdit}
                    addOrEdit={addOrEdit} />
            </Popup>
            <Notification
                notify={notify}
                setNotify={setNotify}
            />
            <ConfirmDialog
                confirmDialog={confirmDialog}
                setConfirmDialog={setConfirmDialog}
            />
    </>
  )
}

Upvotes: 1

Views: 9334

Answers (1)

Elisabeth Whiteley
Elisabeth Whiteley

Reputation: 91

I've been struggling with styling the pagination component myself, but just got it working using sx.
Try with something like this:

 <TablePagination
    sx={{
      '.MuiTablePagination-toolbar': {
        backgroundColor: '#a9aeb3',
        width: '950px',
        color: 'rgb(41, 39, 39)',
        height: '35px',
      },
    }}
/>

Edit: I tried styling "everything" just to see how it would be done, look here for ideas if there was something else you needed to style.

 <Pagination
    {...mTablePaginationProps}
    rowsPerPage={rowsPerPage}
    onRowsPerPageChange={onRowsPerPageSelect}
    component="div"
    onPageChange={onPageChange}
    sx={{
      backgroundColor: 'red !important', // gets overridden if not important
      height: '70px',
      '.MuiInputBase-root': {
        backgroundColor: 'green',
      },
      '.MuiTablePagination-toolbar': {
        backgroundColor: 'pink',
        width: '950px',
        color: 'rgb(41, 39, 39)',
        height: '35px',
      },
      '.MuiBox-root': {
        backgroundColor: 'yellow',
        color: 'black',

        '& .MuiSvgIcon-root': {
          backgroundColor: 'purple',
          color: 'black',
        },
      },
    }}
    SelectProps={{
      ...mTablePaginationProps.SelectProps,
      MenuProps: {
        ...mTablePaginationProps.SelectProps.MenuProps,
        sx: {
          '.MuiPaper-root': {
            backgroundColor: 'rosybrown',
            color: 'black',
          },
          '.MuiTablePagination-menuItem': {
            ':hover': {
              backgroundColor: 'turquoise',
            },
            backgroundColor: 'yellow',
          },
          '.MuiTablePagination-menuItem.Mui-selected': {
            ':hover': {
              backgroundColor: 'blue',
            },
            backgroundColor: 'purple',
          },
        },
      },
    }}
  />

This ends up looking like this: Horribly styled table pagination

Upvotes: 2

Related Questions