Filtering by a single field(status) in a table component

Viewed 57

I have a table made with table component in ui material. Exactly what I want to do, I just want to filter the status field. When I click on the filterlist button above, filtering will be opened only for the status field, or when a filtering icon is clicked directly next to the status header, it will open.

I don't want to use datagrid. I want to do it with Table component. Is there a way to do it?

enter image description here

import React from "react";
import styled from "styled-components/macro";
import { NavLink } from "react-router-dom";
import { makeStyles } from "@material-ui/core/styles";
import { Helmet } from "react-helmet-async";
import { useDispatch } from "react-redux";
import {
  setPartner,
  setPartnerStatus,
} from "../../redux/actions/partnerActions";

import {
  Button,
  Box,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  Paper as MuiPaper,
  MaterialTable,
  Modal,
  Table,
  TableBody,
  TableContainer,
  TableCell,
  TableHead,
  TablePagination,
  TableRow,
  TableSortLabel,
  Toolbar,
  Tooltip,
  Typography,
  FormControlLabel,
  Switch,
} from "@material-ui/core";

import { FilterList as FilterListIcon, MoreVert } from "@material-ui/icons";

import { spacing } from "@material-ui/system";
import PartnerRequest from "../../pages/pages/PartnerRequest";
import { orange } from "@material-ui/core/colors";

const Paper = styled(MuiPaper)(spacing);

const Spacer = styled.div`
  flex: 1 1 80%;
`;

function descendingComparator(a, b, orderBy) {
  if (orderBy === "registiratedDate") {
    return new Date(b[orderBy]).valueOf() - new Date(a[orderBy]).valueOf();
  }
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

function getComparator(order, orderBy) {
  return order === "desc"
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort(array, comparator) {
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

const headCells = [
  {
    id: "organizationName",
    numeric: false,
    disablePadding: false,
    label: "Organization Name",
  },
  {
    id: "firstName",
    numeric: false,
    disablePadding: false,
    label: "Fist Name",
  },
  { id: "lastName", numeric: false, disablePadding: false, label: "Last Name" },

  {
    id: "createdDate",
    numeric: false,
    disablePadding: false,
    label: "Created Date",
  },

  {
    id: "partnerStatusId",
    numeric: false,
    disablePadding: false,
    label: "Status",
  },
  {
    id: "actions",
    numeric: true,
    disablePadding: false,
    label: "Actions",
  },
];

const Badge = styled.span`
  font-size: 11px;
  background-color: ${(props) => props.color};
  color: white;
  border-radius: 8px;
  padding: 4px 8px;
  text-align: center;
`;

const MoreVertIcon = styled(MoreVert)({
  cursor: "pointer",
  marginLeft: "-20px",
  "&:hover": {
    opacity: ".7",
  },
});

function EnhancedTableHead(props) {
  const { onSelectAllClick, order, orderBy, rowCount, onRequestSort } = props;
  const createSortHandler = (property) => (event) => {
    onRequestSort(event, property);
  };

  return (
    <TableHead>
      <TableRow>
        {headCells.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={headCell.numeric ? "center" : "left"}
            padding={headCell.disablePadding ? "none" : "default"}
            sortDirection={orderBy === headCell.id ? order : false}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : "asc"}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

let EnhancedTableToolbar = (props) => {
  return (
    <Toolbar>
      <div>
        <Typography variant="h6" id="tableTitle">
          Partner Requests
        </Typography>
      </div>
      <Spacer />
      <div>
        <Tooltip title="Filter list">
          <IconButton aria-label="Filter list">
            <FilterListIcon />
          </IconButton>
        </Tooltip>
      </div>
    </Toolbar>
  );
};

const Backdrop = styled("div")`
  z-index: -1;
  position: fixed;
  right: 0;
  bottom: 0;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.2);
  -webkit-tap-highlight-color: transparent;
`;
const useStyles = makeStyles((theme) => ({
  paper: {
    width: "500px",
    height: "420px",
    backgroundColor: orange,
  },
}));

function EnhancedTable({ partners }) {
  const [order, setOrder] = React.useState("asc");
  const [orderBy, setOrderBy] = React.useState("calories");
  const [selected, setSelected] = React.useState([]);
  const [page, setPage] = React.useState(0);
  const [dense, setDense] = React.useState(false);
  const [rowsPerPage, setRowsPerPage] = React.useState(5);

  const [open, setOpen] = React.useState(false);
  const dispatch = useDispatch();
  // const handleChange = (event) => {
  //   setAge(Number(event.target.value) || "");
  // };

  const handleClose = () => {
    setOpen(false);
  };

  const handleRequestSort = (event, property) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
  };

  const handleSelectAllClick = (event) => {
    if (event.target.checked) {
      const newSelecteds = partners.map((n) => n.name);
      setSelected(newSelecteds);
      return;
    }
    setSelected([]);
  };

  // const handleClick = (event, name) => {
  //   const selectedIndex = selected.indexOf(name);
  //   alert(selectedIndex);
  //   // let newSelected = [];

  //   // if (selectedIndex === -1) {
  //   //   newSelected = newSelected.concat(selected, name);
  //   // } else if (selectedIndex === 0) {
  //   //   newSelected = newSelected.concat(selected.slice(1));
  //   // } else if (selectedIndex === selected.length - 1) {
  //   //   newSelected = newSelected.concat(selected.slice(0, -1));
  //   // } else if (selectedIndex > 0) {
  //   //   newSelected = newSelected.concat(
  //   //     selected.slice(0, selectedIndex),
  //   //     selected.slice(selectedIndex + 1)
  //   //   );
  //   // }

  //   // setSelected(newSelected);
  // };

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleChangeDense = (event) => {
    setDense(event.target.checked);
  };

  const isSelected = (name) => selected.indexOf(name) !== -1;
  const partnersLength = partners ? partners.length : 0;
  const emptyRows =
    rowsPerPage - Math.min(rowsPerPage, partnersLength - page * rowsPerPage);

  function PartnerStatus({ partnerStatusId }) {
    let statusName, color;

    if (partnerStatusId === 1) {
      statusName = "Open";
      color = "#54AAD1";
    } else if (partnerStatusId === 2) {
      statusName = "Accepted";
      color = "#76C893";
    } else if (partnerStatusId === 3) {
      statusName = "Rejected";
      color = "#EF233C";
    }
    return <Badge color={color}>{statusName}</Badge>;
  }

  return (
    <div>
      <Paper>
        <EnhancedTableToolbar />
        <TableContainer>
          <Table
            aria-labelledby="tableTitle"
            size={dense ? "small" : "medium"}
            aria-label="enhanced table"
          >
            <EnhancedTableHead
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={partnersLength}
            />
            <TableBody>
              {stableSort(partners || [], getComparator(order, orderBy))
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((row, index) => {
                  const isItemSelected = isSelected(row.name);
                  const labelId = `enhanced-table-checkbox-${index}`;

                  return (
                    <TableRow
                      hover
                      // onClick={(event) => handleClick(event, row.name)}
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={row.id}
                      selected={isItemSelected}
                    >
                      <TableCell component="th" id={labelId} scope="row">
                        {row.organizationName}
                      </TableCell>
                      <TableCell align="left">{row.firstName}</TableCell>
                      <TableCell align="left">{row.lastName}</TableCell>
                      <TableCell align="left">
                        {new Date(row.createdDate).toLocaleDateString("uk-UK")}
                      </TableCell>
                      <TableCell align="left">
                        {/* <Badge color={row.partnerStatusId}>
                          {row.partnerStatusId}
                        </Badge> */}
                        <PartnerStatus partnerStatusId={row.partnerStatusId} />
                      </TableCell>
                      <TableCell align="center">
                        <MoreVertIcon
                          // onClick={handleClickMoreVertIcon.bind(row.id - 1)}
                          onClick={() => {
                            dispatch(setPartner(partners[row.id - 1]));
                            setOpen(true);
                          }}
                        />

                        <Modal
                          open={open}
                          onClose={handleClose}
                          aria-labelledby="simple-modal-title"
                          aria-describedby="simple-modal-description"
                          BackdropComponent={Backdrop}
                        >
                          <PartnerRequest handleClose={handleClose} />
                        </Modal>
                        {/* <Dialog
                          disableEscapeKeyDown
                          open={open}
                          onClose={handleClose}
                          BackdropComponent={Backdrop}
                          className={classes.paper}
                        >
                          <DialogContent>
                            <PartnerRequest handleClose={handleClose} />
                          </DialogContent>
                        </Dialog> */}
                      </TableCell>
                    </TableRow>
                  );
                })}
              {emptyRows > 0 && (
                <TableRow style={{ height: (dense ? 33 : 53) * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={partnersLength}
          rowsPerPage={rowsPerPage}
          page={page}
          onChangePage={handleChangePage}
          onChangeRowsPerPage={handleChangeRowsPerPage}
        />
      </Paper>
      <FormControlLabel
        control={<Switch checked={dense} onChange={handleChangeDense} />}
        label="Dense padding"
      />
    </div>
  );
}

function PartnerRequestsTable({ partners }) {
  return (
    <React.Fragment>
      <Helmet title="Partner Requests" />

      <Grid container spacing={6}>
        <Grid item xs={12}>
          <EnhancedTable partners={partners} />
        </Grid>
      </Grid>
    </React.Fragment>
  );
}

export default PartnerRequestsTable;

0 Answers
Related