2

How to change/customize the default color of selected rows in a Material-UI table (of type Sorting & Selecting)? By default it is secondary (red) color (Codesandbox here: https://codesandbox.io/s/3sjxh). How to change it to a custom color, or at least to primary (blue), as it appears in the new beta version (https://next.material-ui.com/components/tables/#main-content) (v5).

Table with selected row in default red color

1 Answers1

4

You have to pass your styles to the classes props in order to change the styles for the TableRow.

To achieve the background-color change you want to override the default classes: .MuiTableRow-root.Mui-selected and .MuiTableRow-root.Mui-selected:hover.

To override them you have to use a parent reference with a so called $ruleName in your makeStyles hook. Here is a very good explanation from @Ryan Cogswell if you are more interested how it works.

This would then look like this:

const useStyles = makeStyles((theme) => ({
  // your other styles
  ...,
  tableRowRoot: {
    "&$tableRowSelected, &$tableRowSelected:hover": {
      backgroundColor: theme.palette.primary.main
    }
  },
  tableRowSelected: {
    backgroundColor: theme.palette.primary.main
  }
}));

...

<TableRow
  // your other props
  ...
  classes={{
    root: classes.tableRowRoot,
    selected: classes. tableRowSelected,
  }}
>
  ...
</TableRow>;

For the checkboxes, you only have to add the color prop in order to change it:

<Checkbox
  // other props
  ...
  color="primary"
/>

and for your Toolbar, you only need to change the provided highlight class inside your useToolbarStyles in order to get things working:

import { alpha } from "@material-ui/core/styles";

...

const useToolbarStyles = makeStyles((theme) => ({
  ...,
  highlight:
    theme.palette.type === "light"
      ? {
          color: theme.palette.primary.main,
          backgroundColor: alpha(
            theme.palette.primary.light,
            theme.palette.action.selectedOpacity
          )
        }
      : {
          color: theme.palette.text.primary,
          backgroundColor: theme.palette.primary.dark
        },
}));

Live demo:

Edit change-color-of-selected-row-on-material-ui-table

yun_jay
  • 1,050
  • 6
  • 20
  • Thank you very much! I thought it was pointing in that direction but didn't know about $ruleName. And thanks for the link too, very informative indeed! – Carlos D. Zapata Aug 01 '21 at 18:59