Udesh
Udesh

Reputation: 2071

material-table How do I select a row changing the background color upon selection

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

Upvotes: 3

Views: 9978

Answers (2)

Lowkey
Lowkey

Reputation: 836

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

Upvotes: 6

Chris B.
Chris B.

Reputation: 5763

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

I forked your sandbox here.

Upvotes: 2

Related Questions