How to multiple select the table row in React-table using the ctrl And Shift Click?

Viewed 323

Code:-

<table {...getTableProps()} className="table">
  <thead>
    {headerGroups.map((headerGroup) => (
      <tr {...headerGroup.getHeaderGroupProps()} id="header-fixed">
        {headerGroup.headers.map((column) => (
          <th {...column.getHeaderProps()}>{column.render("Header")}</th>
        ))}
      </tr>
    ))}
  </thead>
  <tbody {...getTableBodyProps()}>
    {rows.map((row, i) => {
      prepareRow(row);
      return (
        <tr
          {...row.getRowProps({
            onClick: () => {
              console.log("ROW", row.id);
            }
          })}
          className="border_bottom"
          tabIndex={i}
          onKeyDown={(e) => handleKeyDown(e, i)}
          onLoad={() => active(i)}
          ref={i === 0 ? myRef : null}
        >
          {row.cells.map((cell) => {
            return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
          })}
        </tr>
      );
    })}
  </tbody>
</table>

Table row Image i want when user click with shift + mouse click on first row and then last row btw them all rows are selected with the row id ?is this possible to do?

Plz help....

1 Answers

I needed this feature as well, and couldn't find a great solution for it. The issue I had, was that I had no way to save the previously selected row, which is needed for the multi-select calculation. I ended up using the useRowState hook to keep this value saved. I'm sure this is not the intended use of this hook, but at least it works. I hope somebody can use the implementation too:

Cell: (cellProps: CellProps<TaskData>) => {
        const { row, toggleRowSelected, setRowState, state } = cellProps;
        
        const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
            const prevSelectedRow = state.rowState?.prevSelectedRow;
            if (event.target.checked) {
                setRowState(['prevSelectedRow'], row.id[0]);
                toggleRowSelected(row.id, true);
            } else {
                setRowState(['prevSelectedRow'], undefined);
                toggleRowSelected(row.id, false);
            }
            if ((event.nativeEvent as PointerEvent)?.shiftKey && prevSelectedRow){
                const current = parseInt(row.id);
                const previous = parseInt(prevSelectedRow.toString());
                if (previous < current) {
                    for (let i = previous; i < current; i++) {
                        toggleRowSelected(i+'', true);
                    }
                } else {
                    for (let i = current; i > previous; i++) {
                        toggleRowSelected(i+'', true);
                    }
                }
            }
        }
        return <input checked={state.selectedRowIds[row.id] ?? false} onChange={handleChange} type={'checkbox'}/>
    },
Related