javascriptreactjsradio-buttonreact-tablereact-table-v7

Make only one row selectable at a time in React Table 7.1.0


I am trying to implement react table with just one row selectable at at time. I have gone through a lot of examples for multiple rows selection in a react table but in my case, the user can select only one row when the user clicks on the radio button but currently all the rows can be selected. Could anyone help me out on this to implement ?

enter image description here


Solution

  • I know this is an old question, but maybe someone will find this solution useful. Since version 7, react-table provides a stateReducer that can be used to track and change the state of a table. (before v7 it had reducerHandlers, but I didn't go deep into that). You can modify the state as follows:

    useTable(
        {
          columns,
          data,
          stateReducer: (newState, action) => {
              if (action.type === "toggleRowSelected") {
                newState.selectedRowIds = {
                  [action.id]: true
                }
              }
    
              return newState;
          },
        }
        ...
    

    Here is the CodeSandbox with the changes described