mardi 3 mars 2020

In React-Table, how to check/uncheck all checkbox in a row or column

I have a table using react-table with checkboxes in rows. I also added a "check all" checkbox in the 1st cell of a row, to check/uncheck all the checkboxes in every column of that row.

The problem is when I implemented the "check all" checkbox, it worked as intended but when I check/uncheck a checkbox individually it doesn't check/uncheck.

Table Component

import setTableColumns from '../utils/setTableColumns';

const RolePermissionsTable = () => {
  return (
    <ReactTable
      defaultPageSize={10}
      data={capacity.roles}
      columns={setTableColumns()}
      showPagination={false}
      getTrProps={(state, rowData, column, instance) => {
        return {
          onClick(event) {
            const row = event.currentTarget;
            const targetEntity = row.querySelector(
              '.RoleTarget [type="checkbox"]'
            );
            const allCheckboxes = Array.prototype.slice.call(
              row.querySelectorAll('[type="checkbox"]')
            );
            const permissionsCheckboxes = allCheckboxes.slice(
              1,
              allCheckboxes.length
            );
            const isChecked = targetEntity.checked;

            permissionsCheckboxes.map(permissionsCheckbox => {
              permissionsCheckbox.checked = isChecked ? isChecked : null;
            });
          },
        };
      }}
    />
  );
};

Column Headers

// imported above for the table
const setTableColumns = () => {
  return [
    {
      Header: 'Entities',
      accessor: 'target',
      Cell: rowData => (
        <span className="RoleTarget" key={rowData.original.target}>
          <input
            id={`CheckAll-${rowData.original.target}`}
            type="checkbox"
          />
          <span className="RoleTarget__name">{rowData.original.target}</span>
        </span>
      ),
    },
    {
      Header: 'Add',
      accessor: 'add',
      Cell: rowData => {
        return (
          <input
            type="checkbox"
            defaultChecked={rowData.original.permissions.add}
            id={`${rowData.original.target}-${rowData.original.userId}`}
          />
        );
      },
    },
    {
      Header: 'Modify',
      accessor: 'modify',
      Cell: rowData => {
        return (
          <input
            type="checkbox"
            defaultChecked={rowData.original.permissions.modify}
            id={`${rowData.original.target}-${rowData.original.userId}`}
          />
        );
      },
    },
    {
      Header: 'Delete',
      accessor: 'delete',
      Cell: rowData => {
        return (
          <input
            type="checkbox"
            defaultChecked={rowData.original.permissions.delete}
          />
        );
      },
    },
  ];
};

I'm not sure if I'm doing this correctly or is there a better way for this?

Many thanks




Aucun commentaire:

Enregistrer un commentaire