React-table select row without checkbox

Viewed 4013

Hello can I select a row in React-table without using the checkbox, I want just to use a click on the row that we want to select and then fetch the data from the selected row, if that's feasible can you provide me with an example

2 Answers

Edit: this answer is now outdated and is in need of revision. If you use React-Table at v7 please consult the official documentation for examples of how to make rows in your table clickable.


You need to register an event listener for your Row components, which would detect clicks. When listener is invoked, you will be able to change the state of your application to record that user has made a selection, which, in turn, can be used to change the appearance of the table so that users can "see" the selection happen (e.g. change the background color of the rows).

If using modern react-table based on custom Hooks API

You can pass onClick handler to row.getRowProps function to add it to all tr elements. You can also use row.setState to set row as selected.

<tbody {...getTableBodyProps()}>
    {rows.map((row, i) => {
        return (
            <tr {...row.getRowProps({
                onClick: () => { /* select the row here */ } 
            })}>
                {row.cells.map(cell => {
                    return /* your cell code */
                })}
            </tr>
        )
    })}
</tbody>

If using react-table@v6 and earlier

Use <ReactTable /> component prop called getTrProps which accepts a function which will receive information about the row and should return all props you want the tr element to receive — for example:

<ReactTable
    getTrProps={(_, row) => {
        return {
            onClick: () => { /* select your row here */ }
        };
    }}
/>

If you're using react-table v7.7.0 custom Hooks API, For row level click follow below steps.

First pass useRowSelect hook to useTable like below.

   const tableInstance = useTable(
    {
        columns,
        data,
    },
    useRowSelect);

then you can add onClcik to tr

  <tbody>
    {rows.map((row, i) => {
      prepareRow(row)
      return (
        // <tr {...row.getRowProps()}>
        <tr {...row.getRowProps()} onClick={() => { console.log(' row click ', row)}} >
          {row.cells.map(cell => {
            return (
              <td {...cell.getCellProps()}>
                {cell.render('Cell')}
              </td>
            )
          })}
        </tr>
      )
    })}
  </tbody>

Note: If useRowSelect not passed to useTable. onClick on <tr> wont trigger. Same way any option like filtering or sorting ect. pass respective hooks like useFilters or useSortBy to useTable will make it work.

Related