Carlos D. Zapata
Carlos D. Zapata

Reputation: 139

Change color of selected row on Material UI table

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

Upvotes: 2

Views: 8343

Answers (1)

yun_jay
yun_jay

Reputation: 1180

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

Upvotes: 6

Related Questions