3

Using the material-table library. I would like to replicate the behavior shown in this example.

https://codesandbox.io/s/table-hover-colors-zw9nt

https://www.npmjs.com/package/material-table https://material-table.com/#/ enter image description here

I was thinking of using onRowClick={}

The logic would be

onRowClick =>

  1. set value in component state that renders clicked rows background to a different color
  2. set all other rows to background to the original color

I can use conditional rendering based on a value held in state to change the background. Although this changes the background for all rows.

options={
   rowStyle:{backgroundColor: this.state.selected ? '#fff' : this.state.c}
}

enter image description here

My current working example is here https://codesandbox.io/s/peaceful-haibt-2nefw

Thanks for your help

Udesh
  • 1,919
  • 3
  • 20
  • 26

2 Answers2

6

You also need to pass the selectedRowId otherwise everything will be blue. Also, the rowStyle options accept a callback, which you could invoke like so:

rowStyle: rowData => ({
backgroundColor: this.state.selected && rowData.tableData.id === this.state.selectedRowId 
?   this.state.c
    : "#fff" 
})

Your onRowClick also needs some work (the select/unselect condition was not correct). https://codesandbox.io/embed/select-one-row-160vm

Lowkey
  • 836
  • 5
  • 12
2

The package's documentation provides an example of how you can accomplish this with the options prop.

I forked your sandbox here.

Chris B.
  • 5,477
  • 1
  • 12
  • 30