javascriptreactjsreact-nativeonclickonhover

Coloring Table rows onHover and onClick using React


I have been trying to color my Table when onHover and onClick event happen via both js and css, but I have the same issue with both.. if cursor leaves the <tbody> the active is instantly reverted to old color.

What I would like to do is that when you click on a row in the table then it stays active until a click is made on another row.

For css solution I was using this:

.hoverClass:hover {
  background: red;
}
.hoverClass:active {
  background: yellow;
}

And for js solution:

  onTableRowClicked = (e) => {
    this.setState({ currentColoringTarget: e });
    e.currentTarget.style.background = "#EEE55E";
  };

  changeTableRowBackgroundOnMouseOver = (e) => {
    e.currentTarget.style.background = "#EEEEEE";
  };

  changeTableRowBackgroundOnMouseOut = (e) => {
    e.currentTarget.style.background = "transparent";
  };

...
<tbody
  onClick={(e) => this.onTableRowClicked(e)}
  onMouseOver={this.changeTableRowBackgroundOnMouseOver}
  onMouseOut={this.changeTableRowBackgroundOnMouseOut}
>
  <tr>
    <th className="vertically-aligned-th">
      <strong>1)</strong>
    </th>
    <th className="vertically-aligned-th">21314</th>
    <th className="vertically-aligned-th">address2</th>

    <th>
      <Button className="acceptButton">Accept</Button>
    </th>
    <th>
      <Button className="declineButton">Decline</Button>
    </th>
  </tr>
</tbody>
...

Here is a CodeSandBox with the code.


Solution

  • You were going in the right direction, but rather than touching the DOM directly via style.backgroundColor you can use some React state to track the ID of the row and then apply a selected class which handles the styling.

    I've updated the sandbox to give you an idea how to do this. https://codesandbox.io/s/elegant-lewin-duqt6?file=/src/App.js

    NOTE: I've only applied the row selection for the first two rows of the top table. This solution will need DRYing out, but should give you an idea how to achieve it.