Modify the current style of the MUI table

I'm working on a table with sorting functionality similar to the mui website's "sorting and selecting" feature: https://material-ui.com/components/tables/

My goal is to modify the color of the header text that is selected for sorting. I attempted the following code snippet, but was only successful in changing the background-color (simplified example):

const useStyles = makeStyles({
  active: {
    color: "yellow",
    backgroundColor: "yellow",
  },
});

function Example() {
  const classes = useStyles();
  // functions for sorting etc. here left out
  return (
  <TableContainer component={Paper}>
      <Table>
          <TableHead>
              <TableRow>
               <StyledTableCell>
                    <TableSortLabel
                      active={valueToOrderBy === "column"}
                      direction={
                        valueToOrderBy == "column" ? orderDirection : "asc"
                      }
                      onClick={createSortHandler("column")}
                      classes={{ active: classes.active }}
                    >
                      column
                    </TableSortLabel>
                  </StyledTableCell>
                 </TableRow>
          </TableHead>
        <TableBody>
        // data that comes in the column
       </TableBody>
         </Table>
        </TableContainer>
        )}

When clicking on the column, it sorts correctly and changes the background-color of the header text to yellow, but doesn't change the text color. I also experimented with modifying the theme's active and selected colors, but had no success.

Answer №1

This issue has already been addressed in a response here.

The main problem lies within the definition of the color in the selector root&$active. The selector active is merely used as a "pseudo" element, as shown in the source code.

To properly override both properties, utilize the following code:

const useStyles = makeStyles({
  root: {
    '&$active': {
      color: "yellow",
      backgroundColor: "yellow",
    },
  },
  active: {}, // pseudo
});

...

<TableSortLabel
  active={valueToOrderBy === "column"}
  direction={
    valueToOrderBy == "column" ? orderDirection : "asc"
  }
  onClick={createSortHandler("column")}
  classes={{ root: classes.root, active: classes.active }}
>
  column
</TableSortLabel>

For further reference, check out this Codesandbox link

Answer №2

const customTheme = establishCustomTheme({
  elements: {
    MuiTableSortLabel: {
      styleAdjustments: {
        base: {
          shade: "teal",
          "&:hover": {
            shade: "ivory"
          },
          "&.Mui-active": {
            "&&": {
              shade: "ivory",

              "& * ": {
                shade: "ivory"
              }
            }
          }
        },
        indicator: {
          shade: "ivory"
        }
      }
    }
  }
});


     <UseProvider theme={customTheme}>
{/* Content for the table's header section*/}
    </UseProvider>

Visit this CodeSandBox link for reference.

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

Varied spacing between horizontal and vertical items in a list

The issue with the spacing between horizontal and vertical list items is perplexing. Despite having identical margin, padding, height, and width, they seem to display differently. While manual adjustment of margins or paddings can resolve this, I am curiou ...

When attempting to transition from using fontawesome npm to hosting it yourself, the term "define" is not recognized

I'm currently working on a Gatsby project that originally utilized FontAwesome 5 Pro NPM registry. However, Font Awesome has recently made the decision to discontinue their pro npm registry and now requires a paid subscription for access. In order to ...

Looking for a way to add a CSS effect that reveals another image or text when hovering over an image?

My company's website features 10 country flags that, when clicked, display the entire site in that country's language for the user's session. However, I want to take it a step further and have a small image of the respective country appear w ...

Is there a way to stop mUI from displaying the dropdown menu once Chrome automatically fills in a user's address details?

I am currently developing a form for users to enter their address in order to collect a billing address for payment information. Our services are only available to customers within the United States, so we have implemented an autocomplete UI component with ...

Navigate between tabs with a single click

Hey there! I'm having trouble putting together a webpage that features a sidebar. I want to make it so that clicking on one of the links at the top will switch the tab and its content accordingly. However, the current code I have isn't working an ...

My website is being cut off

After creating this website with a viewport setup, I noticed that it is not fully visible on certain screens. When viewed on a CRT monitor at 800x600 desktop resolution or lower than 1280x800, such as on mobile devices, the content gets clipped. Is there a ...

Problem with using Jquery DIY slider for multiple purposes

There seems to be an issue with the DIY Slider that I'm using. Whenever I attempt to use this slider more than once on a single page, the second one fails to function. I have exhausted all possible solutions that come to mind. $(".slider").diyslider ...

Addressing the issue of recurring background in Next.js

While I'm fairly new to using Next.Js, I have some prior experience with it. Recently, I encountered an issue where adding a new JavaScript file and inserting a basic header or paragraph caused the padding to repeat itself, pushing down the content on ...

Integrating Next.js with a authentication provider and a Redux provider

During the development of my Next js project, I incorporated Next auth using import {Provider} from 'next-auth/client' to wrap the <Component /> in _app.js. However, I also want to integrate Redux into the project. This involves importing ...

What is the best way to have a component in React "wait" for state updates?

Currently, I am using React to develop a battleship game. One issue I encountered is when the component loads and I try to map the board array, React throws an error stating "cannot read property board of undefined". After some debugging with console loggi ...

Attempting to divide the main page into quadrants

I want to split my homepage into four equal images without any scrolling. When you click on the website, I want the four images to expand and cover the entire screen with no scrollbars. I've made some progress with my code, but it's not quite the ...

The initialization of <Component> must be completed before Nextjs client can access it

I have a simple use case in Nextjs that involves a NavigationBar component with a search input. <div className="w-full flex flex-row items-center py-5 justify-between"> <div className="w-40"> <Link href="/& ...

Quick guide on prepending text to an IconButton

Is there a way to include custom text before the IconButton in Material UI? Here is the code for the button: <div className={classes.toolbar}> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <Chevron ...

Having trouble establishing a connection with mapDispatchToProps

How can I correctly pass an action to the reducer from my component? Here is my code snippet: import React, { Component } from 'react'; import { Text, View, Button} from 'react-native'; import { connect } from 'react-redux'; ...

Authentication Error: CSRF cookie not detected - Please log in again to access the /login/ page using REACT and DJANGO

After successfully developing the frontend using React and backend with Django, everything was functioning flawlessly on localhost. However, upon deploying the frontend on Heroku and attempting a POST request to log in (with the backend still running on lo ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

I am experiencing an issue with my css dropdown menu appearing incorrectly on both Internet Explorer and Firefox

Chrome and Safari are working perfectly fine, but I encountered an issue with IE and FF where the submenu menu appears on the left side of the main navigation. The website in question is cedumilam.php.cs.dixie.edu. Below is the CSS code I am using: # ...

What could be the reason for data.map not being recognized as a function?

I developed the following React component: import React, { useState } from 'react'; export default function Example(){ var friend = function (id, firstName, lastName){ this.id = id; this.firstName = firstName; this.lastName = lastN ...

Whenever I try to retrieve a file from my backend using formData.get('file'), the FormData functionality inexplicably sends back a null value instead. Even though I

I am encountering an issue while trying to send a file to parse to my backend using Flask. When I send the file using Postman, it works correctly. However, when I attempt to send it through my React app, it does not go through. <div ...

How to perfectly align the toggle button using Bootstrap 3

I have implemented the default nav-bar from Bootstrap 3 in my WordPress theme, with some modifications renaming it '.navbar-custom'. On mobile-sized screens, the default 'toggle' appears in the right corner, while the '.navbar-bra ...