'Material UI responsive grid direction
I want the container direction as "row" above md size screen and "column" below md size screen? How can I implement it?
<Grid container direction = "row"(in large screens)/direction = "column"(in small screens)>
I tried something this.
<Grid container classes={gridDirection}>
gridDirection: {
direction = "row",
[theme.breakpoints.down('md')]: {
direction = "column",
},
}
but it is not working probably because "direction" is a react prop and not a CSS style. Is there a way to access these react props inside stylesheet file?
Solution 1:[1]
You can use useMediaQuery
import useMediaQuery from '@material-ui/core/useMediaQuery';
const largeScreen = useMediaQuery(theme => theme.breakpoints.up('md'));
<Grid container direction={largescreen?"row":"column"}>
Solution 2:[2]
The easiest way and I believe the modern way is to use the sx attribute. Then let MUI handle the breakpoints for you. These are the default MUI breakpoints as of writing.
xs = extra-small: 0px
sm = small: 600px
md = medium: 900px
lg = large: 1200px
xl = extra-large: 1536px
xs and sm are generally considered to be mobile/small tablet. MUI is mobile first, so xs will be set and not overwritten until the size is md or larger in my example below.
<Grid container sx={{ flexDirection: { xs: "column", md: "row"} }}>
</Grid>
Solution 3:[3]
Use flexDirection instead of direction.
gridDirection: {
flexDirection = "row",
[theme.breakpoints.down('md')]: {
flexDirection = "column",
},
}
Solution 4:[4]
At least as on date of answering here, Material UI supports direction
or flexDirection
attributes with component, with these attributes supporting responsive value based on breakpoints mapped object passed to it.
For example, in your case, if direction="row" is needed on large screens and direction="column" is needed for small screens, then the prop can be passed in as:
direction={{xs:'row', lg:'column'}}
, thus letting MUI prop handle it with the Grid element as:
<Grid container direction={{xs:'row', lg:'column'}}> ... </Grid>
This is the right style to use it in your code, for this case, in my opinion, though other alternative answers here also work well.
Solution 5:[5]
in MUI v5 you can do it like below:
<Grid container direction={{xs: "column", md: "row"}}>
</Grid>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kal |
Solution 2 | RollingInTheDeep |
Solution 3 | Mahadev Mandal |
Solution 4 | Harshit Gupta |
Solution 5 | Jagar |