[reactjs] Select row on click react-table

I am trying to find the best table to use with my react apps, and for now, the react-table offers everything I need (pagination, server-side control, filtering, sorting, footer row).

This being said, I can't seem to be able to select a row. There are no examples that show this.

Some things, that I have tried include trying to set a className on click of the row. But I can't seem to find the calling element in e nor t. Also, I don't like this approach, because it is not how a react app should do things.

<ReactTable
            ...
            getTrProps={(state, rowInfo, column, instance) => {
                return {
                    onClick: (e, t) => {
                        t.srcElement.classList.add('active')
                    },
                    style: {
                    }
                }
            }}
        />

Some possible workaround would be to render checkboxes as a first column, but this is not optimal as it limits the area to click to 'activate' the row. Also, the visual feedback will be less expressive.

Am I missing the elephant in the room? And if not, do you know another library that supports the things that I've described earlier?

Thank you!

EDIT: Another option, this being open source, is to suggest an edit. And maybe this is the proper thing to do.

EDIT 2

Another thing, suggested by Davorin RuĆĄevljan in the comments, but I couldn't make it work was:

onRowClick(e, t, rowInfo) {
    this.setState((oldState) => {
        let data = oldState.data.slice();
        let copy = Object.assign({},  data[rowInfo.index]);

        copy.selected = true;
        copy.FirstName = "selected";
        data[rowInfo.index] = copy;

        return {
            data: data,
        }
    })
}

....

            getTrProps={(state, rowInfo, column) => {
                return {
                    onClick: (e, t) => { this.onRowClick(e, t, rowInfo) },
                    style: {
                        background: rowInfo && rowInfo.row.selected ? 'green' : 'red'
                    }
                }
            }}

This sets the 'FirstName' column to 'selected', but does not set the class to 'green'

This question is related to reactjs react-table

The answer is


The answer you selected is correct, however if you are using a sorting table it will crash since rowInfo will became undefined as you search, would recommend using this function instead

                getTrGroupProps={(state, rowInfo, column, instance) => {
                    if (rowInfo !== undefined) {
                        return {
                            onClick: (e, handleOriginal) => {
                              console.log('It was in this row:', rowInfo)
                              this.setState({
                                  firstNameState: rowInfo.row.firstName,
                                  lastNameState: rowInfo.row.lastName,
                                  selectedIndex: rowInfo.original.id
                              })
                            },
                            style: {
                                cursor: 'pointer',
                                background: rowInfo.original.id === this.state.selectedIndex ? '#00afec' : 'white',
                                color: rowInfo.original.id === this.state.selectedIndex ? 'white' : 'black'
                            }
                        }
                    }}
                }

if u want to have multiple selection on select row..

import React from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import { ReactTableDefaults } from 'react-table';
import matchSorter from 'match-sorter';


class ThreatReportTable extends React.Component{

constructor(props){
  super(props);

  this.state = {
    selected: [],
    row: []
  }
}
render(){

  const columns = this.props.label;

  const data = this.props.data;

  Object.assign(ReactTableDefaults, {
    defaultPageSize: 10,
    pageText: false,
    previousText: '<',
    nextText: '>',
    showPageJump: false,
    showPagination: true,
    defaultSortMethod: (a, b, desc) => {
    return b - a;
  },


  })

    return(
    <ReactTable className='threatReportTable'
        data= {data}
        columns={columns}
        getTrProps={(state, rowInfo, column) => {


        return {
          onClick: (e) => {


            var a = this.state.selected.indexOf(rowInfo.index);


            if (a == -1) {
              // this.setState({selected: array.concat(this.state.selected, [rowInfo.index])});
              this.setState({selected: [...this.state.selected, rowInfo.index]});
              // Pass props to the React component

            }

            var array = this.state.selected;

            if(a != -1){
              array.splice(a, 1);
              this.setState({selected: array});


            }
          },
          // #393740 - Lighter, selected row
          // #302f36 - Darker, not selected row
          style: {background: this.state.selected.indexOf(rowInfo.index) != -1 ? '#393740': '#302f36'},


        }


        }}
        noDataText = "No available threats"
        />

    )
}
}


  export default ThreatReportTable;

Multiple rows with checkboxes and select all using useState() hooks. Requires minor implementation to adjust to own project.

    const data;
    const [ allToggled, setAllToggled ] = useState(false);
    const [ toggled, setToggled ] = useState(Array.from(new Array(data.length), () => false));
    const [ selected, setSelected ] = useState([]);

    const handleToggleAll = allToggled => {
        let selectAll = !allToggled;
        setAllToggled(selectAll);
        let toggledCopy = [];
        let selectedCopy = [];
        data.forEach(function (e, index) {
            toggledCopy.push(selectAll);
            if(selectAll) {
                selectedCopy.push(index);
            }
        });
        setToggled(toggledCopy);
        setSelected(selectedCopy);
    };

    const handleToggle = index => {
        let toggledCopy = [...toggled];
        toggledCopy[index] = !toggledCopy[index];
        setToggled(toggledCopy);
        if( toggledCopy[index] === false ){
            setAllToggled(false);
        }
        else if (allToggled) {
            setAllToggled(false);
        }
    };

....


                Header: state => (
                    <input
                        type="checkbox"
                        checked={allToggled}
                        onChange={() => handleToggleAll(allToggled)}
                    />
                ),
                Cell: row => (
                    <input
                        type="checkbox"
                        checked={toggled[row.index]}
                        onChange={() => handleToggle(row.index)}
                    />
                ),

....

<ReactTable

...
                    getTrProps={(state, rowInfo, column, instance) => {
                        if (rowInfo && rowInfo.row) {
                            return {
                                onClick: (e, handleOriginal) => {
                                    let present = selected.indexOf(rowInfo.index);
                                    let selectedCopy = selected;

                                    if (present === -1){
                                        selected.push(rowInfo.index);
                                        setSelected(selected);
                                    }

                                    if (present > -1){
                                        selectedCopy.splice(present, 1);
                                        setSelected(selectedCopy);
                                    }

                                    handleToggle(rowInfo.index);
                                },
                                style: {
                                    background: selected.indexOf(rowInfo.index)  > -1 ? '#00afec' : 'white',
                                    color: selected.indexOf(rowInfo.index) > -1 ? 'white' : 'black'
                                },
                            }
                        }
                        else {
                            return {}
                        }
                    }}
/>

Another mechanism for dynamic styling is to define it in the JSX for your component. For example, the following could be used to selectively style the current step in the React tic-tac-toe tutorial (one of the suggested extra credit enhancements:

  return (
    <li key={move}>
      <button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
    </li>
  );

Granted, a cleaner approach would be to add/remove a 'selected' CSS class but this direct approach might be helpful in some cases.


I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).

If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:

// Any Tr element will be green if its (row.age > 20) 
<ReactTable
  getTrProps={(state, rowInfo, column) => {
    return {
      style: {
        background: rowInfo.row.selected ? 'green' : 'red'
      }
    }
  }}
/>

There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.


enter image description here



After importing the HOC you can then use it like this with the necessary methods:

/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
    // start off with the existing state
    let selection = [...this.state.selection];
    const keyIndex = selection.indexOf(key);

    // check to see if the key exists
    if (keyIndex >= 0) {
        // it does exist so we will remove it using destructing
        selection = [
            ...selection.slice(0, keyIndex),
            ...selection.slice(keyIndex + 1)
        ];
    } else {
        // it does not exist so add it
        selection.push(key);
    }
    // update the state
    this.setState({ selection });
}

/**
* Toggle all checkboxes for select table
*/
toggleAll() {
    const selectAll = !this.state.selectAll;
    const selection = [];

    if (selectAll) {
        // we need to get at the internals of ReactTable
        const wrappedInstance = this.checkboxTable.getWrappedInstance();
        // the 'sortedData' property contains the currently accessible records based on the filter and sort
        const currentRecords = wrappedInstance.getResolvedState().sortedData;
        // we just push all the IDs onto the selection array
        currentRecords.forEach(item => {
            selection.push(item._original._id);
        });
    }
    this.setState({ selectAll, selection });
}

/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
    return this.state.selection.includes(key);
}

<CheckboxTable
    ref={r => (this.checkboxTable = r)}
    toggleSelection={this.toggleSelection}
    selectAll={this.state.selectAll}
    toggleAll={this.toggleAll}
    selectType="checkbox"
    isSelected={this.isSelected}
    data={data}
    columns={columns}
/>

See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable

Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw