Display checkboxes on all TableRow elements as soon as one of them is checked

I've incorporated a material-ui Table into my project and have successfully implemented multi-select functionality. Here are the requirements I've fulfilled so far:

  • Checkboxes are initially hidden - COMPLETED
  • Hovering over a row reveals its checkbox - COMPLETED
  • Once one Checkbox is checked, all other Checkbox elements on different rows should remain visible.

While I have achieved the first two requirements, I am struggling to accomplish the final one.

How can I make all checkboxes visible (by adjusting the opacity) when any one of them is checked?

Below is my current progress:

https://codesandbox.io/s/hover-table-row-checkbox-11ozf?fontsize=14&hidenavigation=1&theme=dark

import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
TableBody from "@material-ui/core/TableBody";
TableCell from "@material-ui/core/TableCell";
TableContainer from "@material-ui/core/TableContainer";
TableHead from "@material-ui/core/TableHead";
TableRow from "@material-ui/core/TableRow";
Paper from "@material-ui/core/Paper";
Checkbox from "@material-ui/core/Checkbox";

const useStyles = makeStyles({
rowIconStyle: {
minWidth: 50,
minHeight: 50
},
tableRowStyle: {
cursor: "pointer",
"&hover": {
backgroundColor: "darkGrey"
}
},
rowSelectionCheckboxStyle: {
//opacity: "calc(var(--oneRowSelected))",
opacity: 0,
"$tableRowStylehover &": {
opacity: 1
}
}
});

export default function MyTableComponent(props) {
const styles = useStyles();
const DEFAULT_TABLEROWICONCOLOR = "grey";
return (
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>
<Checkbox className={styles.rowSelectionCheckboxStyle} />
</TableCell>
<TableCell>Icon</TableCell>
<TableCell>Name</TableCell>
</TableRow>
</TableHead>
<TableBody>
{props.tableRowsData.map(row => {
const RowIcon =
row.icon && row.icon.iconElement
? row.icon.iconElement
: ()=> <div />;
let iconElement = (
<RowIcon
className={styles.rowIconStyle}
style={{
color:
row.icon && row.icon.color
? row.icon.color
: DEFAULT_TABLEROWICONCOLOR
}}
/>
);
return (
<TableRow key={row.name} className={styles.tableRowStyle}>
<TableCell>
<Checkbox className={styles.rowSelectionCheckboxStyle} />
</TableCell>
<TableCell>{iconElement}</TableCell>
<TableCell>{row.projectName}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
);
}

MyTableComponent.propTypes = {
tableRowsData: PropTypes.array
};

Answer №1

Make sure to have both a value and an onChange function in your Checkbox component. Create a state variable to keep track of the selected checkboxes and update it when there is a change in the checkbox selection. Apply the class styles.rowSelectionCheckboxStyle only if at least one checkbox is checked.

Check out a functional version of your code here

export default function MyTableComponent(props) {
  const [checkedRows, setCheckedRows] = useState({});
  const styles = useStyles();
  const DEFAULT_TABLE_ROW_ICON_COLOR = "grey";

  const anyChecked = () => {
    let anyRowChecked = false;
    for (let key in checkedRows) {
      if (checkedRows[key]) {
        anyRowChecked = true;
      }
    }
    return anyRowChecked;
  };

  const handleChecked = (isChecked, index) => {
    setCheckedRows(prevState => ({ ...prevState, [index]: isChecked }));
  };

...
...
return (
              <TableRow key={row.name} className={styles.tableRowStyle}>
                <TableCell>
                  <Checkbox
                    checked={checkedRows[index]}
                    onChange={e => handleChecked(e.target.checked, index)}
                    className={
                      !anyChecked() && styles.rowSelectionCheckboxStyle
                    }
                  />
                </TableCell>
                <TableCell>{iconElement}</TableCell>
                <TableCell>
                  {checkedRows[index] ? "True" : "False"} {row.projectName}
                </TableCell>
              </TableRow>
            );
          })}
...

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

Despite having a result, the Promise is returning an undefined value

In Vuejs, I have a method named getUsers that takes an array as input and fetches user data from the database. When calling it like this, it successfully returns the results: this.getUsers(executives).then( result => { this.speci ...

Checking if the current time falls within a specific time range, without taking the year into account, using Javascript

I am looking to add a special feature using JavaScript. I would like to change the background images of my webpage to ones related to Christmas during the holiday week, and have it repeat every year. How can I determine if the current date and time fall ...

Are Gatsby Server-Side Rendering APIs and Next.js SSR the equivalent in functionality?

After mastering Gatsby Js for building an ecommerce website using the SSR method, I am now contemplating between sticking with Gatsby or switching to Next for future scalability as web technology advances and user base expands. Which option would be bett ...

The parent element of a 3D div is causing issues with hovering and clicking on the child elements

In my scenario, the parent div is transformed in 3D with rotation, causing it to move to the backside. The issue arises with the child div containing a button that becomes unclickable due to the parent div position. Setting backface-visibility to hidden al ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...

Recording web browser network traffic using JavaScript

Is there a method in webdriverio that allows me to capture and validate the response of API calls made by the browser while loading data for my automated tests? https://i.sstatic.net/TMExU.png ...

Adjust the width of columns using HTML and CSS

UPDATED: Here is a real-life scenario I am facing: I am trying to adjust the width of columns in my table using inline CSS. Let me provide you with an example: The Table was initially set to 100%, like this: <table width=100% ...> The total number ...

Different methods of displaying the next image from a URL without explicitly setting the dimensions

I am attempting to display an image in Next.js without specifying the width and height by using import Image from 'next/image';. It should be noted that the image is sourced from a URL, not a specific folder within the project. <Image si ...

What is the best method for eliminating an element from an array when a specific key is

Essentially, the dataSource for the kendo grid has a default data called selVal. If any key from selval matches with dtoVal, I want to delete everything from selVa. Is it possible to implement this with the code below? It's not deleting selVal element ...

When a CSS fluid layout includes a containing div with margin or padding, it may lead to

On my jsfiddle , the outermost wrapper div has a width of 100%. I am trying to create an inner div (tb_margin or tb_padding) where the content starts 40px from the left. I have attempted to use both margin and padding for this left spacing, but in both cas ...

Ways to correct the input label for OutlinedInput

I've been experimenting with Material UI while working on a project that required creating a TextField with a mask using react-imask: https://mui.com/en/material-ui/react-text-field/#integration-with-3rd-party-input-libraries However, when I tried u ...

Utilize leaflet to display points on a map

I have a substantial amount of data points (around 150k) stored in my database, and I am looking to retrieve them using an axios request and display them on a map within my application built on the PERN stack. What would be the most effective approach fo ...

Transform the file format from .casa-model to .obj

Looking for a way to convert a file with the extension .casa-model to .obj format. Is there any solution available? Find the model here. ...

Is it possible to modify a single value in a React useState holding an object while assigning a new value to the others?

In my current state, I have the following setup: const [clickColumn, setClickColumn] = useState({ name: 0, tasks: 0, partner: 0, riskFactor: 0, legalForm: 0, foundationYear: 0 }) Consider this scenario where I only want to update ...

Concentrate on Managing Text Input Fields in Zend Form

I designed a form using Zend Form and want the focus to be on a text area within the form when the page loads. I attempted to use JavaScript for this purpose, but it only briefly shows the focus before removing it again, preventing any typing. I considere ...

Unable to logout with ExpressJS passport-local

After pasting the passport-local app into my own, I noticed something interesting: I managed to successfully log in users, but for some reason, I can't seem to get them logged out. app.get('/logout', function(req, res){ req.logout(); r ...

Can the functionality of a button be disabled after being clicked a total of 5 times?

Once a user clicks the button five times, I plan for it to be disabled. Can this be achieved solely with HTML, or would JavaScript be necessary? ...

The returned type of intersected functions in Typescript does not match the inferred type

While attempting to extract the return type of an intersected request, I encountered a discrepancy between the return type and the inferred type. Check out the shortened URL for more details: https://tsplay.dev/mAxZZN export {} type Foo = (() => Promis ...

Understanding the document.domain feature in Javascript

I have a website called foo.com hosted on server bar. Within this website, I have created a subdomain called api.foo.com. To connect the subdomain with Google Apps, I have set up a CNAME entry pointing to ghs.google.com. Now, I am facing an issue when att ...

Equal gutters are present between CSS floats

After conducting various experiments, I have devised a method to incorporate fixed and equal gutters between floats. My approach involves using positive and negative margins as well as multiple wrappers, making the solution somewhat cumbersome. However, I ...