Customize the background color of a Material UI row with varying colors for each cell

I am facing an issue with a Material UI table in React 18 where each cell has a different background color, causing the hover style on the row to break. Despite trying various solutions, I have been unable to find a resolution.

For reference, you can see the desired outcome here:

When hovering over a row in the table, the color should simply darken.

Is there a straightforward way to accomplish this using React and Material UI? How can I ensure that the entire row changes color when hovered over?

While I can set a different color for individual cells when in the hover state from my Cell component, it only applies to single cell hovers, not the entire row.

export const MyCustomCell = (props) => {
    const theme = useTheme();
    return (
        <TableCell
            style={{
                backgroundColor: getCellBackground(props)
            }}
            sx={{
                "&.MuiTableCell-root:hover": {
                    backgroundColor: getCellBackgroundOnHover(props)
                }
            }}
        >
            {betterTiming(prop)}
        </TableCell>
    )
}
 <TableRow
            role="checkbox"
            sx={{
                '&:last-child td, &:last-child th': {border: 0},
                // "&.MuiTableRow-root:hover": {
                //     backgroundColor: "pink !important"
                // }
            }}
            tabIndex={-1}
        >
</TableRow>

EDIT: The color is computed dynamically from props

Answer №1

Despite my best efforts to find a solution through Google search, I ultimately resorted to using a hover state in React.

const [rowHovered, setRowHovered] = React.useState(false);

   const handleRowHover = () => {
        setRowHovered(true);
    };

    const handleRowLeave = () => {
        setRowHovered(false);
    };

    return (
        <TableRow
            role="checkbox"
            onMouseEnter={handleRowHover}
            onMouseLeave={handleRowLeave}
        >
        <MyCustomCell hovered={rowHovered} />
</TableRow>
export const MyCustomCell = (props) => {
    const theme = useTheme();

    return (
        <TableCell
            style={{
                backgroundColor: getCellBackgroundColor(props, props.hovered)
            }}
        >
            ...
        </TableCell>
    )
}

Subsequently, getCellBackgroundColor will determine the color based on my specific business logic.

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

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

Adjust the vertical size of the slider in Jssor

Hi there! I'm currently working on a slider that I want to have a dynamic width (100% of the container) and a static height of 550px on PCs, while being responsive on mobile devices. Below is my code snippet: <div class="col-md-6 right-col" id="sl ...

What is the reason behind the delayed mutation of the state when invoking the setState method in React?

Currently diving into the Forms section within the documentation of ReactJS. Just implemented this code snippet to showcase the use of onChange (JSBIN). var React= require('react'); var ControlledForm= React.createClass({ getInitialState: f ...

Issue encountered while attempting to store quantity in localStorage

Currently, I am developing a shopping cart feature for my website and I would like to display the total quantity of items in the header. I have implemented useReducer and context to manage the state of my items within the application, which is functioning ...

Transforming color images into black and white using JavaScript

     I have implemented this code to convert colored images to grayscale. function applyGrayscaleEffect() {         var imageData = contextSrc.getImageData(0, 0, width, height);         var data = imageData.data;         var p1 = 0.99;   ...

When toggling between light and dark themes using the useMediaQuery hook, the Material-ui styling is being overridden

While working with next.js and material-ui, I encountered an issue where the theme would change based on user preference. However, when switching to light mode, the JSS Styles that I had set were being overwritten. This problem only seemed to occur in ligh ...

What is the best way to achieve this particular grid layout using html and css?

I have a CSS grid of icons and I am trying to create a divider between each cell that fades in opacity towards the edges, similar to an airbrush effect. However, I want the cells themselves to remain transparent so that the background pattern is still visi ...

Encountering a problem during the installation of Firebase through npm: receiving an unexpected error message stating "Unexpected end of

Having some difficulty installing Firebase in my new React project, I am unable to get it installed. Not sure if it's an error or just taking a long time with npm. It has been over half an hour and still waiting. ...

Different ways to adjust the positioning of the HTML canvas created using p5.js

I am attempting to integrate the output canvas from p5.js into my webpage by following a tutorial heretutorial. I am hoping that the canvas will appear where I have positioned it within the HTML body. However, no matter what I try with CSS properties like ...

Guide on handling asynchronous data return within a reducer

I'm struggling to properly handle the state when receiving data from the back-end of my application. This is the code I have: if (action.type === actionTypes.getList) { const id = action.payload.userId; Axios.post(`${apiUrl}/lists`, { ...

Navigate through content to reach the bottom of the webpage

I am currently working on a layout that is similar to Facebook's messaging system (facebook.com/messages). I have made some progress with it, but not quite there yet. You can view my work so far here: https://jsfiddle.net/3nd0b17m/23/ The main issue ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

NextJs Link component does not refresh scripts

While using the <Link> tag in NextJs for page navigation, I encountered an issue where my scripts do not rerun after switching pages. The scripts only run on the initial page load or when I manually reload the page. This behavior is different when us ...

Is the navigation dropdown toggle triggered by both mouseout and when hovering off of it?

I'm looking for some assistance in modifying the code so that the dropdown menu not only hides on click, but also hides on mouseout and/or when another top-level menu button is hovered over. View jsfiddle example $(document).ready(function () { ...

The functionality of the disabled and checked options on the radio button seems to be malfunction

Within an Angular HTML document, I have a set of radio buttons that share common names. I am attempting to update their disabled and checked properties from a .ts file, but the changes are not taking effect. Here is the code snippet: let elements = docume ...

What is the best practice for importing modules in React Native: MainActivity.java or MainApplication.java?

While integrating this module into my React Native project, the documentation suggests importing it in MainActivity.java. However, in my previous project where I have used it, I imported all modules including this one in MainApplication.java. In which fi ...

How to align li elements at center in a Bootstrap navbar

I'm having trouble centering link1 and link2 both horizontally and vertically on the page. The horizontal alignment is working fine, but I can't seem to get the vertical alignment right, no matter what I try. Here is the HTML code snippet: ...

A step-by-step guide to setting up a custom splash screen for React Native

Looking for assistance in setting up a splash screen in react-native specifically for Android devices. I've managed to successfully implement one for iOS, but I'm encountering difficulties when it comes to getting one to work on Android. I' ...

Creating a dynamic background image with automatic cropping techniques: How to do it?

I'm currently working on a custom wordpress theme and I've encountered an issue that I need help with. I want to have a wide background image on my homepage with text centered on it, but I also want the height to remain the same as the browser w ...

Adding a script to the head of a Next.js page by using the Script component

I need assistance with inserting tracking code from Zoho application into the Head section of each page in my Next.js application. I am currently using a _document.tsx file and following the instructions provided by Next.js regarding the use of the Next.js ...