Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic styles in MUI sx prop? [duplicate]

Is is possible to use dynamic styles in the MUI sx prop? Something like this:

<Box
  key={index}
  sx={{
    height: "100%",
    width: "100%",
    {index === imgIndex &&
    {"@keyframes fadeIn": {
        from: {
            opacity: 0,
        },
        to: {
            opacity: 1,
        },
        },
        "fade-in": {
        animation: "$fadeIn 2.5s",
        }}}
    }}
>
  {child}
</Box>

If not, what options are there to do something like this?

My use case is this is a refactor of a carousel that was done with MUI4 (makeStyles) and I'm migrating to MUI5 (no more makeStyles)

like image 904
bonum_cete Avatar asked Oct 22 '25 07:10

bonum_cete


1 Answers

You can do it by having the condition against the property itself rather than inside the object.

Here is an example of how you can change the bgColor of a box when you click a button

import Box from "@mui/material/Box";
import Button from "@mui/material/Button";

export default function BoxSx() {
  const [clicked, setClicked] = React.useState(false);

  const handleClick = () => {
    setClicked(!clicked);
  };

  return (
    <>
      <Button onClick={handleClick}>Change</Button>
      <Box
        sx={{
          width: 300,
          height: 300,
          bgcolor: clicked ? "primary.dark" : "secondary.light",
        }}
      />
    </>
  );
}

like image 154
Richard Hpa Avatar answered Oct 24 '25 22:10

Richard Hpa