React-Table: How to change the background color of a row if it is clicked (selected) with the mouse?

20,421

Please see here for an answer: Select row on click react-table

Here is my code:

First of all you need a state:

  this.state = {
    selected: -1
  };

-1 is important because otherwise the row with the index 0 will be highlighted without clicking on it.

And getTdProps looks like this:

getTrProps={(state, rowInfo, column, instance) => {
    if (typeof rowInfo !== "undefined") {
        return {
            onClick: (e, handleOriginal) => {
                this.setState({
                selected: rowInfo.index
                });
                if (handleOriginal) {
                handleOriginal()
                }
            },
            style: {
                background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
                color: rowInfo.index === this.state.selected ? 'white' : 'black'
            },
        }
    }
    else {
        return {
            onClick: (e, handleOriginal) => {
                if (handleOriginal) {
                handleOriginal()
                }
            },
            style: {
                background: 'white',
                color: 'black'
            },
        }
    }
}}
Share:
20,421
dergroncki
Author by

dergroncki

Software Engineer, Jazz and more 🎹 🎷 🎸

Updated on July 16, 2022

Comments

  • dergroncki
    dergroncki almost 2 years

    I have the following code for retrieving data of the clicked row:

        <ReactTable
          getTdProps={(state, rowInfo, column, instance) => {
            return {
              onClick: (e, handleOriginal) => {
                if (typeof rowInfo !== "undefined") this.rowClick(rowInfo.row.RecipeName);
                if (handleOriginal) {
                  handleOriginal()
                }
              }
            }
          }}
    

    How can I change the background color of the clicked row? Or what is the best way to highlight the clicked row?