I am planning to write a custom mui grid. Grid will behave differently for different viewport.
for XL it is working as expected but not for tablet and small device viewport.
For Tablet, I need gutter 24px and width of each item inside container auto where margin outside container, will be 37px.
For small device, columns would be 4 and width will be auto and gutter will be 8px
working code for XL is as below
import React from "react";
import Grid2 from "@mui/material/Unstable_Grid2"; // MUI Grid2
import { SxProps, Theme } from "@mui/material";
interface MyGridProps {
container?: boolean;
gridColumn?: number;
size?: { [key: string]: number }; // Responsive sizes
sx?: SxProps<Theme>; // Accept custom styles
children?: React.ReactNode;
}
const MyGrid: React.FC<MyGridProps> = ({
container = false,
gridColumn = 12,
size,
sx = {},
children,
}) => {
const calculateItemStyles = (breakpoint: string): SxProps<Theme> => {
if (size && size[breakpoint]) {
const cols = size[breakpoint];
const width = cols * 70; // Each column is 70px wide
return {
flexBasis: `${width}px`,
maxWidth: `${width}px`,
};
}
return {};
};
return (
<Grid2
container={container}
columns={gridColumn}
sx={{
...(container && {
borderSizing: "border-box",
flexWrap: "wrap",
justifyContent: "center",
gap: "32px", // Default gap for container
"@media (min-width:1440px)": {
gap: "32px",
},
}),
...(!container && {
...calculateItemStyles("xs"),
"@media (min-width:568px)": calculateItemStyles("sm"),
"@media (min-width:1280px)": calculateItemStyles("xl"),
"@media (min-width:768px)": {
...calculateItemStyles("md"),
gap: '24px'
},
}),
...sx, // Merge custom styles
}}
>
{children}
</Grid2>
);
};
export default MyGrid;