Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

react-table

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?

like image 547
dergroncki Avatar asked Apr 03 '18 13:04

dergroncki


1 Answers

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'
            },
        }
    }
}}
like image 112
dergroncki Avatar answered Sep 18 '22 08:09

dergroncki