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)
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",
}}
/>
</>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With