enableRowSelection in useTable

Viewed 71

I'm not too familiar with useReactTable, however I need to make use of useTable to conditionally select certain rows based on some conditions.

Below is the useReactTable equivalent of what I want to achieve:

const table = useReactTable({
    data,
    columns,
    state: {
      rowSelection
    },
    enableRowSelection: (row) => row.original.age > 18, //This is what I want to achieve with useTable
    onRowSelectionChange: setRowSelection,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    debugTable: true
  });

The checkbox at any particular row should only be selectable if the users age is more than 18.

How can that be achieved with useTable in React?

Thanks

Update:

I was able to get the rows disabled based on some conditions, but there is another bigger problem, which is that when I use the Select All checkbox at the top of the table, I see even the disabled checkboxes still getting checked, I don't want that. Below is a screenshot of the behavior I don't want

enter image description here

A disabled checkbox should never get checked even when Select All is used

1 Answers

You can add disabled property to checkboxes and control if they are checked not or not based on a condition. I used official row-selection-example to test.

function Table({ columns, data }) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    selectedFlatRows,
    state: { selectedRowIds },
  } = useTable(
    {
      columns,
      data,
    },
    useRowSelect,
    hooks => {
      hooks.visibleColumns.push(columns => [
        // Let's make a column for selection
        {
          id: 'selection',
          // The header can use the table's getToggleAllRowsSelectedProps method
          // to render a checkbox
          Header: ({ getToggleAllRowsSelectedProps }) => (
            <div>
              <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
            </div>
          ),
          // Disabled and not checked if age < 13
          Cell: ({ row }) => (
            <div>
              {row.original.age >= 13 ? <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />  
              : <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} disabled={true} checked={row.original.age >= 13 ? true : false} />}
            </div>
          ),
        },
        ...columns,
      ])
    }
  )
Related