Is there a way to change the color of multiple adjacent cells when hovering over one cell, and can this be done dynamically (so the number of adjacent cells that change color can vary)?
Here is the code snippet:
I'm using React to create a table with the following code:
<TableBody>
<TableRow>{tableRowGen()}</TableRow>
</TableBody>
The tableRowGen
function looks like this:
const tableRowGen = () => {
let cells = [];
for (var i = 0; i < columnNumber; i++) {
cells.push(
<TableCell
className={classes.td}
onMouseEnter={() => {
console.log("hi!");
}}
align="center"
>
{i}
</TableCell>
);
}
console.log(cells);
return cells;
};
Currently, I have a style for table cell hover effect (td
) which turns the background red:
td: {
...
"&:hover": {
background: "#f00",
},
},
Example shown below:
This is how it currently looks:
https://i.stack.imgur.com/7ygFA.png
But is it possible to make cells 4 and 5 turn red when hovering only over 3? (as seen below)
https://i.stack.imgur.com/GHSID.png
EDIT:
Updated tableRowGen
function code:
const tableRowGen = () => {
let cells = [];
for (var i = 0; i < columnNumber; i++) {
cells.push(
<TableCell
// className={classes.td}
align="center"
onMouseEnter={() => onMouseEnter(i)}
onMouseLeave={onMouseLeave}
className={Math.abs(hoveredCell - i) <= 14 ? classes.td : ""}
>
{i}
</TableCell>
);
}
return cells;
};
Additional code based on suggestions:
const [hoveredCell, setHoveredCell] = React.useState(null);
const onMouseEnter = React.useCallback((index) => {
setHoveredCell(index);
}, []);
const onMouseLeave = React.useCallback(() => {
setHoveredCell(null);
}, []);