To dynamically adjust a component's height and apply styles in a React project using Material-UI (MUI), you can use the sx prop, the styled utility, or directly customize with CSS-in-JS. Here's a simple approach using the sx prop:
Example: Adjusting Height Dynamically with the sx Prop
The sx prop is a shorthand for styling MUI components and supports theme-aware styling.
import React from "react";
import Box from "@mui/material/Box";
function DynamicHeightBox({ height }) {
return (
<Box
sx={{
bgcolor: "primary.main",
height: height ? `${height}px` : "auto", // Dynamically adjust height
p: 2,
boxShadow: 3,
}}>
This box has dynamic height!
</Box>
);
}
export default function App() {
return <DynamicHeightBox height={200} />;
}