how to use state in sx prop for selecting child in MUI

Viewed 61

I have a table row and I want to style the cell based on the state i.e, activeColNo. How can I use CSS nth-child selector with value activeColNo in sx prop.

<TableRow
   sx={{
      "& :nth-child({activeColNo})": {
         bgcolor: "red"
       } 
   }}
>

Something like this, but it does not work. What are the possible solutions for it?

3 Answers

Once try this

<TableRow
   sx={[
      {
        `&:nth-child(${activeColNo})`: {
          bgcolor: "red"
        } 
      }
   ]}
>

you can try this:

const child = document.querySelector(`&:nth-child(${activeColNo})`);
child.style.color = yourCondition ? "red" : "yellow";

The approach that worked for me is conditionally providing style object to sx prop. I have used map to render cells inside row. The colNo in the below snippet comes from index parameter of map.

{
  rows.map((row, index) => {
    let colNo = index + 1; //Adding 1 for my specific use case
    return (
      <TableCell
        align="center"
        sx={
          colNo == activeColNo && {
            bgcolor: "red",
          }
        }
      >
        {row.value}
      </TableCell>
    );
  });
}

If you want to avoid warning use ternary operator with empty object for failed case, because sx prop needs object

sx={
     colNo == activeColNo ? {
                bgcolor: "#a4f2be"
              } : {}
   }
Related