Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal:

I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. These properties can be used to color the cells in both TableHead and TableBody.

Within the TableHead component, I am leveraging a TableSortLabel similar to the example demonstrated in the material-ui documentation here: https://material-ui.com/components/tables/#sorting-amp-selecting

My objective is to dynamically change the text and arrow icon colors on hover and when active based on user-provided props.

Let's examine how the colors of the TableSortLabel behave in different scenarios: Initially, the text color is grey with no arrow visible. When hovered over, a grey arrow appears alongside black text. Upon clicking, an active state is triggered where both the grey arrow and text turn black permanently until the active state is removed.

My Attempts so Far:

const useStyles = makeStyles({
  tableSortLabel: props => ({
    backgroundColor: "blue",
    color: props.headCellColor,
    fill: props.headCellColor,
    "&:hover": {
      backgroundColor: "blue"
    }
  })
});

function EnhancedTableHeadCell(props) {
  const { isActive, onHoverSortState, clickHandler, ...otherProps } = props;
  const classes = useStyles(props.styles);

  return (
    <FancyTableCell styles={props.styles} {...otherProps}>
      <TableSortLabel
        active={isActive}
        classes={{
          icon: classes.tableSortLabel,
          active: classes.tableSortLabel
        }}
        direction={onHoverSortState}
        onClick={clickHandler}
      >
        {props.children}
      </TableSortLabel>
    </FancyTableCell>
  );
}

This is what it looks like in the browser:

The first image depicts a normal header, the second showcases the hover effect, and the third illustrates the active state after being clicked.

Upon observation, it is clear that the text color remains unaffected by the color css property in all three instances (normal, hover, active). While the backgroundColor impacts the icon but not the text during hovering, we notice that the backgroundColor does affect the text when the component is active. The behavior aligns as expected with the icon, the only discrepancy lies with the text.

What could be causing this issue? How can I troubleshoot and resolve it?

Answer №1

Here is what worked for me:

const CustomStyledTableSortLabel = withStyles((theme: Theme) =>
createStyles({
    root: {
      color: 'white',
      "&:hover": {
        color: 'white',
      },
      '&$active': {
        color: 'white',
      },
    },
    active: {},
    icon: {
      color: 'inherit !important'
    },
  })
)(TableSortLabel);

If you want to learn more about increasing CSS specificity, check out: https://material-ui.com/customization/components/#pseudo-classes

Answer №2

Here is the solution to your issue:

MuiTableSortLabel: {
      root: {
        color: textPrimary,

        // if you want to keep icons visible at all times
        // '& $icon': {
        //   opacity: 1,
        //   color: primaryMain
        // },

        "&:hover": {
          color: primaryMain,

          '&& $icon': {
            opacity: 1,
            color: primaryMain
          },
        },
        "&$active": {
          color: primaryMain,

          // && instead of & is a workaround for https://github.com/cssinjs/jss/issues/1045
          '&& $icon': {
            opacity: 1,
            color: primaryMain
          },
        },
      },
    }

This redesigned style is applied globally through my ThemeProvider, but you can also implement it individually in your specific component using "withStyles" HOC (refer to "BootstrapButton" in the example)

Answer №3

Successfully implemented in Mui5:

sx = {
    {
        '&.MuiTableSortLabel-root': {
            color: 'white',
        },
        '&.MuiTableSortLabel-root:hover': {
            color: 'blue',
        },
        '&.Mui-active': {
            color: 'blue',
        },
        '& .MuiTableSortLabel-icon': {
            color: 'blue !important',
        },
    }
}

'&.MuiTableSortLabel-root' <-- without space &.

'&.Mui-active' <-- without space &.

'& .MuiTableSortLabel-icon' <-- with space

Answer №4

Struggling to find a suitable method, I devised a temporary fix by overriding the material ui css.

To implement this workaround, I included the following code in my global css:

.MuiTableSortLabel-root.MuiTableSortLabel-active,
.MuiTableSortLabel-root:hover,
.MuiTableSortLabel-icon {
  color: inherit !important;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to prevent a MaterialUI Expansion Panel from automatically expanding

I am currently seeking a solution to automatically set the Expansion panel to expanded=false when the panel is disabled. Picture an expanded Expansion panel. Then, an event triggers and the Expansion Panel becomes disabled. The issue lies in the fact that ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

React-admin CheckboxGroupInput automatically selects certain checkboxes upon loading

How can I set some checkboxes to be checked by default? <CheckboxGroupInput source="my_junction_table" choices={choices} optionText={<KioskCheckbox />} initialValue={[{ id: 4, checked: true }]} // no effect defaultValue={[{ id: 4, check ...

When you log a JavaScript array after making a call using $.ajax, it may return an index

I am experiencing an issue with my array of 10 elements. When I log their key, value pairs in a loop, they are correctly ordered. $.each( sArray, function(i, k) { log(i, k); // log(i, k) returns correctly // [0] ELEMENT ONE // [1] ELEMENT TW ...

I need assistance with a feature on my website where a new form is added every time the invite button is clicked, and the form is deleted when the delete button is

Invite.js This invite component includes an invite button outside the form and a delete button inside the form. The goal is to delete the form when the delete button is clicked. I have utilized useState and sourced this form from material-ui. Can anyone ...

Relationship between multiple Mongoose instances linking to a single entity

Having an issue regarding mongoose and relationships. My "Athletes" collection has the following schema: var athletesSchema = mongoose.Schema({ name : String, regionName : String, age : Number, overallScore : Number, scores : { ordinnal : String, ...

What is the best way to align the logo image in the center of the header vertically?

I am trying to vertically center my logo, but I have not been successful with using margin: auto or margin: center. Here is what I have tried so far: ・text-align: center; ・margin: auto; ・margin: center: ・navbar-brand-center The logo currently app ...

Vue.js 2: Keep an eye on changes, but wait until after the initial data fetch

I recently entered the Vueverse (using Vue.js 2) and I'm encountering some challenges with the watch feature. When the component is mounted, I fetch data from an API and use it to set the value of a radio button. Essentially, I have two radio buttons ...

Using C# to block specific sections of HTML code

Suppose I need to prevent a specific HTML code from running on a website using WebBrowserControl1. I attempted approaches like WebClient1.DownloadFile("website.html", @"C:\BlockerWork"), File.ReadAllText(@"C:\BlockerWork"), String.Replace, follow ...

Bi-weekly Calendar Gathering

I am able to get my events sorted by day with the following code: daysOfWeek: [2], However, I have not been able to find any information in the documentation on how to make it sort fortnightly. Can this be done with fullcalendar? Solution: Just a heads ...

Issue with Internet Explorer 7 causing table to display with added height

Currently investigating why there is additional space being added by IE. The only fixed data is the width of the image (171 px). Using Jquery, I checked the height of the div in Firefox, Chrome, and Opera which came out to 164px, but in IE 7 it's 172 ...

Switch to copy values from one field to another in Formik

Hey there! I'm currently working on a form using Formik within NextJS and I have integrated a switch to allow users the option of using their contact details for invoicing purposes. While I have separate fields for both contact details and invoice de ...

Ways to showcase the content of a page once the controller variables have been set

As someone who is just starting out with AngularJS and web development, I am curious to know if there is a way to delay the display of a page until after all of the controller's $scope variables have been initialized. Most of my $scope variables are c ...

What is the best way to make a gradient fill and rounded border with CSS?

I am interested in creating a gradient and rounded border similar to the top bar on Instagram. Although I know how to create a rounded and solid border, this one utilizes a gradient. It appears that Instagram uses a canvas, but I am wondering if it can b ...

Tips for determining if a player (canvas) is in contact with a drawn wall for collision detection

I created a 2D map using the canvas HTML element where I drew a red square to represent the player and a light blue wall underneath it. I am looking for a way to detect if the player (red square) is in contact with the wall (light blue). The elements do no ...

Troubleshooting data mapping in React applications

Can anyone tell me why I am having trouble mapping through the todos? I'm following an online tutorial and my code is exactly the same as the example, but for some reason it's not iterating through the data. I can see the todos in the client-side ...

Determine whether the object is facing the specified position

I'm attempting to verify whether an object (this.target) is facing towards a particular position (newPosition). Here's what I currently have: new THREE.Matrix4().lookAt( newPosition, this.target.position, this.target.up ) == this.target.matrix ...

Issue with extended waiting times in polling

I am currently working on a chatroom using the long poll method. However, I'm facing an issue where every time a long poll occurs and I refresh the page in Chrome or try to send another async request, everything times out. This means I can't load ...

Authentication via Google and Facebook

Seeking assistance with integrating Google and Facebook authentication into my website. The front end is built using ReactJS, back end with NodeJS, and MongoDB as the database. Any guidance on how to implement this would be greatly appreciated. ...

The dynamic sidebar menu in Adminlte 3 with bootstrap-4 loaded from ajax is not functioning properly, presenting issues with sidebar

Is there a way to fetch dynamic sidebar menu data from the database using AJAX in the adminlte 3 dashboard along with bootstrap 4? I have tried loading the sidebar menu data dynamically using AJAX, but the sidebar open/close functionality is not working pr ...