Tips for customizing the appearance of a specific cell in the first column of a Material UI table

Currently, I am modifying the material ui table found in this codesandbox link. My goal is to adjust the style of the first column's cell in the table when it is selected to match the image provided below. https://i.sstatic.net/DGubN.png

It seems like I may be making a mistake somewhere, but I'm unsure of what it could be. How can I specifically apply styling to only the selected cell in the table without affecting the entire row? Any help or guidance would be greatly appreciated. Thank you.

Answer №1

When utilizing the className={classes.tableCell} for all the instances of <TableCell />, make sure to apply it only to the first one.

import React, { useState } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";

const styles = (theme) => ({
  root: {
    width: "100%",
    marginTop: theme.spacing.unit * 3,
    overflowX: "auto"
  },
  table: {
    minWidth: 700
  },
  tableRow: {
    "&$selected, &$selected:hover": {
      backgroundColor: "white"
    }
  },
  tableCell: {
    "$selected &": {
      color: "red",
      backgroundColor: "yellow"
    }
  },
  hover: {},
  selected: {}
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const rows = [
  createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
  createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
  createData("Eclair", 262, 16.0, 24, 6.0),
  createData("Cupcake", 305, 3.7, 67, 4.3),
  createData("Gingerbread", 356, 16.0, 49, 3.9)
];

function SimpleTable(props) {
  const { classes } = props;
  const [selectedID, setSelectedID] = useState([]);

  const clickHandler = (id) => {
    const array = [...selectedID];
    const index = array.indexOf(id);
    if (index !== -1) {
      array.splice(index, 1);
      setSelectedID(array);
    } else {
      setSelectedID([...array, id]);
    }
  };

  return (
    <Paper className={classes.root}>
      <Table className={classes.table}>
        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell align="right">Calories</TableCell>
            <TableCell align="right">Fat (g)</TableCell>
            <TableCell align="right">Carbs (g)</TableCell>
            <TableCell align="right">Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <TableRow
              hover
              key={row.id}
              onClick={() => {
                clickHandler(row.id);
              }}
              selected={selectedID.includes(row.id)}
              classes={{ hover: classes.hover, selected: classes.selected }}
              className={classes.tableRow}
            >
              <TableCell
                className={classes.tableCell}
                component="th"
                scope="row"
              >
                {row.name}
              </TableCell>
              <TableCell align="right">{row.calories}</TableCell>
              <TableCell align="right">{row.fat}</TableCell>
              <TableCell align="right">{row.carbs}</TableCell>
              <TableCell align="right">{row.protein}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </Paper>
  );
}

SimpleTable.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(SimpleTable);

https://codesandbox.io/s/divine-river-7svsh?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

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

What is the best way to place a transparent navbar on top of a hero image while also adding a functional button to the hero image?

My navigation bar is set to be transparent on top of my hero image, but the buttons on the hero image are not clickable. The nav-bar has a z-index of 1, while my hero image, text, and button have a z-index of -1. This setup causes the button to be unclick ...

Tips for minimizing the dimensions of images in a slideshow within a gallery

Check out this website: The slideshow images on there are too tall. Can someone assist me in lowering the height of the images? I want both images to be displayed at the same height. Thank you in advance. ...

Firefox not recognizing height attribute in table cells

My dilemma revolves around the fact that my table cells are not displaying at the designated height. Here is the code snippet I am working with: <html> <head> </head> <body> <table style="border: 1px solid black; border-radiu ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

Steps to create an iframe that opens in a new window

I'm facing an issue with the iframe sourced from flickr. My website includes an embedded flickr iframe to showcase a gallery without the hassle of creating a slider, resizing images, and extracting thumbnails. Given that this site belongs to a frien ...

"Revolutionizing the way we navigate: Angular's innovative

Presently, my focus is on incorporating route transitions into my project. I've employed a component that appears on click and triggers the corresponding service function: routeTransition(destination) { if (this.router.url !== destination) { t ...

Create a visually appealing DataGrid cell by incorporating a vibrant colored oval with text or an icon inside

I'm in need of assistance with the mui/x-data-grid plugin. My goal is to display a cell within the grid containing both text and an icon, based on the value of the text. Unfortunately, I have been unable to achieve this so far. Here is the link to the ...

What is the best way to keep a header row in place while scrolling?

I am looking to keep the "top" row of the header fixed or stuck during page scrolling, while excluding the middle and bottom rows. I have already created a separate class for the top row in my header code: view image description ...

Eliminate the mystery overflow in your CSS styling

My website is experiencing overflow on the x axis, even though all vw/width properties are set to 100. I suspect that the .logout element may be causing this issue, but I'm not sure what exactly needs to be modified to resolve it. Any assistance would ...

Logging values does not seem to be working for Material-UI and React Hook Form

I am currently using React-Hook-Form, Zod, and Material-UI to generate Textfield components. The issue I am encountering is that upon form submission, the amount TextField does not display any value. Could there be something missing in my code? Access the ...

Integrating a footer into the enhanced search tab slider

I'm struggling to create a sticky footer like the one on w3schools. Even though I used the same code in my material UI demo, it's not functioning properly. I tried debugging by changing the position from fixed to absolute, but it still isn&apos ...

Unlocking the Power of NextJS Keyframes

After successfully creating a background with 3 images using keyframes in my initial project built with html and css, I decided to recreate the project using NextJS. However, I encountered an issue where the third image does not display in NextJS. Instead ...

Adjust the appearance of elements depending on whether the user has activated dark mode or

What is the most efficient way to implement both dark and light themes in my Vue app? One option is to create a 'dark.scss' file and use the '!important' property to override styles defined in components. Another option is to utilize pr ...

"Customize the underline color of textfields in Material UI's Next Dialog

Is there a way to customize the underline color of a text box within a popup window using my secondary palette color? I've been struggling with this due to the lack of clarity in the documentation. ...

Insert content into a designated DIV

Progress bars are essential for tracking certain metrics. Take a look at the progress bars below: <div id="lifeBar-holder"> <div id="lifeBar"></div> </div> <div id="discretionBar-holder"> <div id="discretionBar"&g ...

Do we still require the material-ui custom touch event? It seems to cause many issues

It has come to my attention that material-ui still relies on a package that appears to be incompatible with new React updates from Facebook. There seems to be some frustration over this issue, making it challenging to keep up with React advancements. Is th ...

I am facing an issue where the text on my website is failing to display properly

I am facing an issue where the text on my website renders normally on Android or Windows, but when I run it on iOS, the text disappears completely. It's as if all the text has been set to display: none; The other elements seem to be tucking in just fi ...

How can I display helperText in a red color using material-ui in reactjs?

My aim is to display the helperText in red color similar to when an error occurs, but I am facing difficulty achieving this. I can't seem to pinpoint where I am making a mistake. Below is the code snippet: class Sample extends React.Component<Prop ...

Placing three div elements within a container, one of which has a height set to auto

I need help arranging 3 divs side by side using float:left. The height for two of the div's (child1 and child3) is fixed, but there is no set height for child2 - I would like child2 to have the same height as the container div. <div id="container ...

CSS properties are ineffective in scaling the image strip

I have a large image strip measuring 130560 x 1080. My goal is to load it into an image tag and use the parent div as a viewport, showing only one section of the image at a time. However, I'm encountering a problem when specifying the height and widt ...