Tips for altering the text color of the highlighted row in a Material UI table

Trying to modify the color of the row text and the background color when selected.

I have managed to adjust the background color, but I am encountering difficulty changing the text color.

<TableRow
        className={classes.tableBody}
      >

tableBody: {
    "&:focus": {
      color: "yellow !important",
      backgroundColor: "#3D85D2 !important",
    },
  },

Answer №1

The background color of the element can be customized in TableRow. To ensure proper specificity and avoid using "!important", you should utilize the "hover" class as demonstrated within the TableRow.

The text color is controlled in TableCell, so this is where you should make adjustments.

To implement a solution, your styles may look like this:

const styles = theme => ({
  tableRow: {
    "&$hover:hover": {
      backgroundColor: "blue"
    }
  },
  tableCell: {
    "&$hover:hover &": {
      color: "pink"
    }
  },
  hover: {}
});

then in the render method:

            <TableRow
              hover
              key={row.id}
              classes={{ hover: classes.hover }}
              className={classes.tableRow}
            >
              <TableCell
                className={classes.tableCell}
                component="th"
                scope="row"
              >
                {row.name}
              </TableCell>

Here's a functional example based on your sandbox link:

https://codesandbox.io/s/k36qlx0l1v?fontsize=14

Another similar example using "selected" instead of "hover":

https://codesandbox.io/s/llyqqwmr79

These examples utilize these styles:

const styles = theme => ({
  tableRow: {
    "&$selected, &$selected:hover": {
      backgroundColor: "purple"
    }
  },
  tableCell: {
    "$selected &": {
      color: "yellow"
    }
  },
  selected: {}
});

and some state management:

 const [selectedID, setSelectedID] = useState(null);

Adjusting the TableRow rendering to:

            <TableRow
              hover
              key={row.id}
              onClick={() => {
                setSelectedID(row.id);
              }}
              selected={selectedID === row.id}
              classes={{ selected: classes.selected }}
              className={classes.tableRow}
            >

In Material-UI v4, there will be updates that simplify customizing styles without overriding them.

v4 introduces global class names for the selected state ("Mui-selected") and for TableCell ("MuiTableCell-root"), making it easier to style with just one class applied to TableRow:

const styles = (theme) => ({
  tableRow: {
    "&.Mui-selected, &.Mui-selected:hover": {
      backgroundColor: "purple",
      "& > .MuiTableCell-root": {
        color: "yellow"
      }
    }
  }
});

https://codesandbox.io/s/table-hover-colors-forked-3vmds?fontsize=14&hidenavigation=1&theme=dark

Answer №2

After trying multiple solutions, this particular one stood out as the most effective for me

const customStyles = theme => ({
  tableRow: {
   '&&:hover': {
      backgroundColor: '#0CB5F3',
    },
   },
});

   <TableRow
      hover
      className={customStyles.tableRow}
    >

Answer №3

const customStyles = makeStyles((theme) => ({
 highlighted: {
    backgroundColor: "green !important",
    "&:hover": {
      backgroundColor: "green !important",
    },
  },
}));

 const customClasses = customStyles();
<TableRow highlighted classes={{highlighted: customClasses.highlighted,}}/>

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

Is the examples folder missing from the repository after installing react-router using npm?

After executing the npm install react-router command, it installs version react-router v1.0.3 which includes an examples directory. However, when running the commands: cd node_modules/react-router ls The resulting output is: CHANGES.md README.m ...

Ensure the placeholder remains front and center, growing in size as it moves vertically

.inpsearch{ border:2px solid #bbb; border-radius:14px; height:29px; padding:0 9px; } .inpsearch::-webkit-input-placeholder { color: #ccc; font-family:arial; font-size:20px; } <input type='search' class='inpsea ...

Automatically switch to the designated tab depending on the URL

Is it possible to automatically activate a specific tab based on the URL structure if my tabs are configured in this way? I am looking for a solution where a link on www.example1.com/notabs.html will redirect to www.example2.com/tabs.html This particular ...

Ways to arrange specific columns within a table

I am facing an issue with aligning text in a table properly. In my table, I have two columns - first column and second column, both with colspan="4": It is supposed to look like this: <tr> <td colspan="4"> First column </td> ...

What's the issue with the addClass function not working as expected?

I am currently integrating the website's navbar using PHP, which is why I am unable to use class="active" to highlight the active tab on my navigation bar individually. To solve this issue, I attempted to add the active class to the corresponding tab ...

Buttons are misaligned and do not align on a straight line

Below is the code output: https://i.stack.imgur.com/avhUu.png I am attempting to enhance the symmetry of these buttons. The minus (-) button appears slightly smaller than the plus (+) button even though they have the same padding. I have experimented w ...

Tips for effectively making REST requests from a ReactJS + Redux application?

I'm currently working on a project using ReactJS and Redux, incorporating Express and Webpack as well. I have successfully set up an API and now need to figure out how to perform CRUD operations (GET, POST, PUT, DELETE) from the client-side. Could so ...

The header template may sometimes fail to load the CSS file

Being new to php, I suspect there is a simple solution that I have yet to discover. I've created a header template for all pages, but the css page changes based on the user's current page. How can I use php to determine how many levels up in a f ...

Font malfunctioning on Microsoft Edge and Internet Explorer

Apologies if this seems like a silly question, but I recently imported a font from my computer into a CSS file. While it displays correctly in Chrome, it's not working in Microsoft Edge or Internet Explorer. Unfortunately, I don't have access to ...

The input 'Query' cannot be matched with the type '[(options?: QueryLazyOptions<Exact<{ where?:"

Using codegen, I've created custom GraphQL hooks and types. query loadUsers($where: UserFilter) { users(where: $where) { nodes { id email firstName lastName phoneNumber } totalCount } } export functio ...

Disable list-group-item-action clicking

I'm looking to maintain the list-group-item-action hover effect that changes the background color while eliminating the click effect that activates it. Is there a way to achieve this? I've already removed the href="#" from the If I remove list-g ...

Using jQuery to toggle CSS properties

I'm having trouble switching between a CSS column layout and a normal layout for a div element with the ID 'article'. The jQuery script I wrote doesn't seem to work properly, as the entire thing disappears. Can anyone advise me on how t ...

Converting UTC Date Time to Full Date Using ES6

Is there a way to transform the date 2021-01-10 12:47:29 UTC into January 10, 2021? I've been attempting to achieve this using moment.js code below, but it seems to be functioning in all browsers except Safari. {moment(video?.createdAt).format(' ...

Trigger the onclick method by selecting an icon within the MUI DataGrid

Currently, I am utilizing the default MUI Dialog model in the "DialogModel.js" component. Additionally, I have integrated another MUI DataGrid component as shown below: // RulesTable.js import * as React from 'react'; import { DataGrid } from &a ...

Tips for showcasing the currently active item in a Bootstrap dropdown menu using jQuery

I am trying to highlight the menu item that is selected in a drop-down menu. I attempted the following code, which works if I prevent the default behavior of the link element, but I do not want to do that. So I tried using local storage instead, but it d ...

Choose a specific date on the Material UI DatePicker

What is the best way to set the initial date to tomorrow or a specific date in the React Material UI's DatePicker component? Snippet of my code <DatePicker name="dueDate" label="Due Date" disablePast /> ...

Is it possible for media queries to effectively support mobile devices?

I have a specific requirement for my <input type="number"> element where I need the up and down spinner buttons to be displayed for selecting the next value. However, on mobile devices, these spinner buttons are not visible. To address this ...

The request to http://localhost:3000/:/localhost:4000 resulted in a 404 error (Not Found)

I'm currently in the process of learning react and nodejs. I've been attempting to call my backend from react using axios and cors, but unfortunately I keep encountering this error: GET http://localhost:3000/://localhost:4000/estudiantes 404 (Not ...

Adjust for browser zoom within Three.js CSSRenderer

I'm currently developing a project in three.js using the CSSRenderer and the challenge I'm facing is ensuring that it displays correctly even when the browser zoom is not set at 100%. So far, it appears that: There isn't a way to forcibly ...

Issue with modal not showing up when page is refreshed

I've successfully implemented a modal using material-ui and redux that pops up when a user clicks on a product. Now, my next goal is to incorporate routing with react-router v6. App.jsx export default function App() { return ( <> ...