React table - Row selection when the header check box is clicked the rows check boxes are not checked

375 views Asked by At

I have this table where i have details about the exam schedule of the students. When i select the checkbox of a particular row and click the delete button that row is deleted. Now the problem is that i also have a checkbox in the header the main job of header is to select all the check boxes and delete all the rows. so when i check the header check box all the data related to all the rows is added to the array but the check box of rows is not checked enter image description here

The header check box is checked and all the data is stored in selectedFlatRows but the row checkboxes are not checked

This is the code:

import {
  useTable,
  useSortBy,
  useGlobalFilter,
  usePagination,
  useRowSelect,
} from "react-table";

import styles from "./BasicTable.module.css";
import { useMemo, useState } from "react";
import { CheckBox } from "./TableCheckBox";
import {
  Box,
  Button,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from "@mui/material";
import SelectComp from "../SelectComp";
import {
  KeyboardDoubleArrowLeft,
  KeyboardDoubleArrowRight,
} from "@mui/icons-material";

function BasicTable({ tableData, tableColumn, addCheck = false, checkBoxFn }) {
  const [deleteOpt] = useState(addCheck);

  const columns = useMemo(() => tableColumn, [tableColumn]);
  const data = useMemo(() => tableData, [tableData]);

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    // rows,
    prepareRow,
    state,
    setGlobalFilter,
    page,
    setPageSize,
    nextPage,
    previousPage,
    canNextPage,
    canPreviousPage,
    gotoPage,
    pageOptions,
    selectedFlatRows,
    pageCount,
  } = useTable(
    {
      columns,
      data,
    },
    useGlobalFilter,
    useSortBy,
    usePagination,
    useRowSelect,
    (hooks) => {
      hooks.visibleColumns.push((columns) => {
        //adding delete column to delete individual row or group of rows
        const checkColumn = {
          id: "selection",
          Header: ({ getToggleAllRowsSelectedProps }) => (
            <CheckBox {...getToggleAllRowsSelectedProps()} />
          ),
          Cell: ({ row }) => (
            <CheckBox
              {...row.getToggleRowSelectedProps()}
              key={row.original.id}
            />
          ),
        };
        if (deleteOpt) {
          return [...columns, checkColumn];
        }
        return [...columns];
      });
    }
  );
  const { globalFilter, pageSize, pageIndex } = state;

  function handleSetPageSize(_, size) {
    setPageSize(Number(size));
  }

  return (
    <Stack spacing={2}>
      <Box className={styles.grid}>
        <Box className={`${styles.filedContainer} ${styles.FC_select}`}>
          <SelectComp
            values={[10, 20, 30]}
            initialValue={pageSize}
            type="selection"
            selectionValue={handleSetPageSize}
            placeholder="table size"
          />
          <Typography>Records</Typography>
        </Box>
        <Box className={`${styles.filedContainer} ${styles.FC_search}`}>
          <Typography>Search :</Typography>
          <TextField
            id="outlined-textarea"
            value={globalFilter || ""}
            type="text"
            onChange={(e) => setGlobalFilter(e.target.value)}
            size="small"
            className={styles.tableSearchFiled}
          />
        </Box>
      </Box>
      <TableContainer component={Paper}>
        <Table aria-label="simple table" {...getTableProps()}>
          <TableHead>
            {headerGroups.map((headerGroup) => (
              <TableRow {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column) => (
                  <TableCell
                    {...column.getHeaderProps(column.getSortByToggleProps())}
                  >
                    {column.render("Header")}
                    <span>
                      {column.isSorted
                        ? column.isSortedDesc
                          ? " "
                          : " "
                        : ""}
                    </span>
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableHead>
          {tableData.length !== 0 ? (
            <TableBody {...getTableBodyProps()}>
              {page.map((row) => {
                prepareRow(row);
                return (
                  <TableRow {...row.getRowProps()}>
                    {row.cells.map((cell) => (
                      <TableCell {...cell.getCellProps()}>
                        {cell.render("Cell")}
                      </TableCell>
                    ))}
                  </TableRow>
                );
              })}
            </TableBody>
          ) : (
            <TableBody>
              <TableRow>
                <TableCell>
                  <Typography color="error" m={2}>
                    No record found
                  </Typography>
                </TableCell>
              </TableRow>
            </TableBody>
          )}
        </Table>
        {deleteOpt && tableData.length !== 0 && (
          <Box className={styles.deleteContainer} m={2}>
            <Button
              variant="contained"
              color="error"
              onClick={() => checkBoxFn(selectedFlatRows)}
            >
              Delete
            </Button>
          </Box>
        )}
      </TableContainer>
      <Box className={styles.tableNavigation}>
        <Typography>
          Page{" "}
          <strong>
            {pageIndex + 1} of {pageOptions.length}
          </strong>{" "}
        </Typography>
        <Box component="span" className={styles.tableNavigation}>
          | Go to page :{" "}
          <TextField
            type="number"
            size="small"
            defaultValue={pageIndex + 1}
            onChange={(e) => {
              const pageNumber = e.target.value
                ? Number(e.target.value) - 1
                : 0;
              gotoPage(pageNumber);
            }}
          />
        </Box>
        <Button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
          <KeyboardDoubleArrowLeft />
        </Button>
        <Button onClick={() => previousPage()} disabled={!canPreviousPage}>
          Previous
        </Button>
        <Button onClick={() => nextPage()} disabled={!canNextPage}>
          Next
        </Button>
        <Button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
          <KeyboardDoubleArrowRight />
        </Button>
      </Box>
      <pre>
        <code>
          {JSON.stringify(
            {
              selectedFlatRows: selectedFlatRows.map((row) => row.original),
            },
            null,
            2
          )}
        </code>
      </pre>
    </Stack>
  );
}

export default BasicTable;

0

There are 0 answers