Is it possible to have an icon change color in a TableRow column when hovering over any part of that particular row?

I am currently using material-ui version 4.9.5.

To illustrate my issue, I have created a simplified example here. I have a Table that is populated with basic JSON data. Each row in the table consists of an icon element along with its corresponding color and hover color:

{
      icon: {
         {
              iconElement: FolderIcon,
              color: "red",
              hoverColor: "green"
         }
      },
      projectName: "Project1"
}

This means that each row can have its own unique icon, color, and hover color.

If you take a look at this image: https://i.stack.imgur.com/IpKfE.png, you'll see the setup visually.

My main challenge lies in figuring out how to trigger the hover effect for the individual icon when the user hovers over any part of that row.

Currently, I have managed to implement a hover trigger for the entire row, causing a background change on hover. However, I am struggling to get the icon itself to change upon hovering within that row. Here's what I have so far:

You can view the code sandbox here: https://codesandbox.io/s/icon-hover-color-table-row-q9uim?fontsize=14&hidenavigation=1&theme=dark

// Your React component code goes here...

If you have any suggestions or solutions to this issue, they would be greatly appreciated.

Answer №1

In the scenario where IE support is not required, you have the option to utilize CSS variables. This approach proves beneficial especially when managing hover colors as data with each icon having a unique hover color.

To begin, define the two colors of interest for each icon as custom CSS properties (--icon-color and --hover-icon-color below):

            const RowIcon =
              row.icon && row.icon.iconElement
                ? row.icon.iconElement
                : () => <div />;
            const iconColor =
              row.icon && row.icon.color
                ? row.icon.color
                : DEFAULT_TABLE_ROW_ICON_COLOR;
            const iconHoverColor =
              row.icon && row.icon.hoverColor ? row.icon.hoverColor : iconColor;
            let iconElement = (
              <RowIcon
                className={styles.rowIconStyle}
                style={{
                  "--icon-color": iconColor,
                  "--hover-icon-color": iconHoverColor
                }}
              />

Subsequently, use these CSS properties within your styles:

const useStyles = makeStyles({
  rowIconStyle: {
    minWidth: 50,
    minHeight: 50,
    color: "var(--icon-color)",
    "$tableRowStyle:hover &": {
      color: "var(--hover-icon-color)"
    }
  },
  tableRowStyle: {
    cursor: "pointer",
    "&:hover": {
      backgroundColor: "darkGrey"
    }
  }
});

https://codesandbox.io/s/icon-hover-color-table-row-ft8vi?fontsize=14&hidenavigation=1&theme=dark

For more insights, refer to this related answer: How do you change a style of a child when hovering over a parent using material-ui jss styles

Answer №2

Came across this solution, not entirely sure if it'll fix your problem but worth trying out for the table:

<TableBody>
{dataTable.map((row, i) => (
     <TableRow key={i} style={{ margin: '10px 20px', height: 25, ...this.getStripedEffects(i) }}>
           ....Columns
     </TableRow>
))}
</TableBody>

Apply Striped Effects

  getStripedEffects(i) {
    return { background: colors[i] };
  }

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

Incorporating a background image into a Material UI theme with CSS styling

When customizing a theme in material UI, one can adjust or override it using the function createMuiTheme. Below is the complete file where this process is carried out: import { createMuiTheme } from '@material-ui/core/styles'; import purple from ...

The recent update to Bootstrap v5 caused a complete disruption in the CSS of our application

My Angular app was originally on Angular 14 and used Bootstrap with SCSS compiled to node-sass/SASS package. It also utilized ng-bootstrap v11 and Bootstrap v4.3.1 for CSS styles. As part of a general upgrade, I needed to update the Angular version to 15. ...

saving a JSON element in a JavaScript array

Currently, I am utilizing AJAX to fetch data from a database using PHP and then converting it into JSON format. <?php echo json_encode($data); ?> This is the AJAX function being used: ajaxCall("getdata.php", container, function (data) { var co ...

Ui Bootstrap (angularjs) sidebar is not functioning properly

I am encountering an issue with a sidenav that I am in the process of creating for one of my projects. The goal is to develop a side menu that shifts the content to the right when opened and returns it to the left when closed, essentially functioning as a ...

How can you animate a CSS fill effect from the border outward?

I've been struggling to find an answer to this seemingly simple question online. Can anyone explain how to animate a fill-in with a specific color of an element, starting at the border? For example, the border expands gradually until the entire shap ...

Check the File Format (not just the Extension) prior to Uploading

When uploading a file within an HTML form, you can validate the extension using JQuery's Validation plugin: <form enctype="multipart/form-data" id="form-id"> <input type="file" name="file-id" id="file-id" /> </form> To validate ...

Updating the page dynamically in React/Redux by making API calls based on user submissions

My current task involves calling an API with Redux, triggering the call based on a form submission. If the query is empty, it should return all lists; otherwise, it should only return lists that match the query. // List.tsx import React, { useEffect, useS ...

Can I change the name of an item in ngRepeat?

When repeating in a view: ng-repeat="item in list" In some scenarios, the 'item' looks like this: { "name": "john", "id": 1 } While in others, it appears as: { "value": { "name": "john", "id": 1 } } Is there a way to rena ...

Displaying child properties in a functional ReactJS component

React version 0.14 introduces the concept of pure functional components, ensuring that the same input always results in the same output. Props are passed as function arguments. // Using ES6 arrow functions with implicit return: const PureComponent = ({url ...

Manipulate the text() function within jQuery as the div is being created

The code $('#box').text("hello") will display "hello" as text. But how can I use it when creating a div in a loop? for(i=0; i<3; i++) { description += "<div id='box'>" + text[i] + "</div>"; } Is there a way to s ...

The React/MUI theme seems to be behaving inconsistently across various components

As a first-time user of React/MUI, I am struggling to implement themes consistently. Let me illustrate my issue with a simple example featuring a Box component: import { createTheme, ThemeProvider } from '@mui/material/styles'; import Box from &a ...

What is the process of creating a parent-child rowspan HTML Table in a Blazor Server Application?

I am currently facing a challenge in my Blazor Server application where I am attempting to present parent-child data with rowspan in an HTML table. The table is being rendered, however, it is not displaying correctly. Here is the JSON data I am working wi ...

What is the best way to line up several elements in a single column?

I am facing a layout challenge with two objects inside a column - a paragraph and an image. I need the image to be positioned at the bottom and the paragraph at the top. I have tried using various Bootstrap classes like "align-items-between" and "align-sel ...

Working with e.charcode in TypeScript allows for easy access to

I'm having trouble understanding why this code snippet is not functioning as expected. const addRate = (e: { charCode: KeyboardEvent }) => { if (e.charCode >= 48) { ... } } The error message I receive states: 'Operator '>=& ...

Having trouble with Javascript files failing to load while hosting a website on digital ocean?

Recently, I developed a web application using an express backend and the ejs view engine. Everything works perfectly fine when tested on my local machine. However, I encountered issues when trying to host it on a digitalocean droplet (Ubuntu 22.10 x64). Af ...

The deconstructed state does not get refreshed within the setState callback

Encountering an issue where breaking down a component's state is causing it to not update within setState: state = { value: 'test', values: ['a', 'b', 'c'], }; ... const { value, values } = this.state; ...

Challenge encountered when attempting to remove elements from an array within a for loop

There seems to be an issue with deleting elements from an array within a for loop. var div = document.querySelector('div'); var array = [ "iPad", "iPod", "iPhone" ]; for (let i = 0; i < array.length; i++) { let p = document.createElement ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

Caution: It is not possible to make updates on a component while inside the function body of another component, specifically in TouchableOpacity

I encountered this issue: Warning: Trying to update a component from within the function body of another component. Any suggestions on how to resolve this? Interestingly, the error disappears when I remove the touchable opacity element. ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...