Etherealm
Etherealm

Reputation: 2484

How to change the style of sorting icon in Material UI table?

I want to make the sorting icons in material table be slightly visible even when they are hidden. Currently the opacity of the icons is 0 when not selected/visible. But I want to change it to 0.4 so that they are slightly visible and when selected the opacity will be 1 so they will be completely visible. Since the icons are part of tableHead and I don't have access to the parent of icons I don't know how to override the styles.

Here's the code that I have tried:

https://codesandbox.io/s/kk7yqr8285?module=%2Fdemo.js

Upvotes: 5

Views: 12540

Answers (1)

Jules Dupont
Jules Dupont

Reputation: 7567

You need to override the internal styles of the TableSortLabel component. Specifically, if you look at the CSS API of TableSortLabel, you'll see that the TableSortLabel has an icon style.

So, first define these styles:

const styles = theme => ({
  // Fully visible for active icons
  activeSortIcon: {
    opacity: 1,
  },
  // Half visible for inactive icons
  inactiveSortIcon: {
    opacity: 0.4,
  },
});

Then, override the icon style in your TableSortLabel using your logic for determining whether a sort icon is active or not:

<TableSortLabel
  classes={{
    // Override with the active class if this is the selected column or inactive otherwise
    icon: ((orderBy === column.id) ? classes.activeSortIcon : classes.inactiveSortIcon ) }}
>

Your initial solution had the right styling and logic, but your inline styles were overruled by the internal styling of the TableSortLabel component. In general, when you want to change the internal styling of a component, you'll need to use overrides like we did here.

If you're not familiar with the concept of defining styles and applying them to components with the classes prop, you can learn about that here. Make sure to check out the code examples both on that page and throughout the rest of the docs.

Upvotes: 6

Related Questions