Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
material-ui Grid empty space component
import React from 'react'
import styled from 'styled-components'
import { withTheme } from '@material-ui/core'
import Grid from '@material-ui/core/Grid'
const HIDDEN = 'hidden'
const GridSupportingHidingAtSpecifiedBreakpoints = styled(Grid)`
@media (min-width: ${(p) => p.theme.breakpoints.values.xs}px) {
display: ${(p: any) => (p.xs === HIDDEN ? 'none' : 'flex')};
}
@media (min-width: ${(p) => p.theme.breakpoints.values.sm}px) {
display: ${(p: any) => (p.sm === HIDDEN ? 'none' : 'flex')};
}
@media (min-width: ${(p) => p.theme.breakpoints.values.md}px) {
display: ${(p: any) => (p.md === HIDDEN ? 'none' : 'flex')};
}
@media (min-width: ${(p) => p.theme.breakpoints.values.lg}px) {
display: ${(p: any) => (p.lg === HIDDEN ? 'none' : 'flex')};
}
@media (min-width: ${(p) => p.theme.breakpoints.values.xl}px) {
display: ${(p: any) => (p.xl === HIDDEN ? 'none' : 'flex')};
}
`
const Presentation: React.FC<any> = (props) => (
<GridSupportingHidingAtSpecifiedBreakpoints item {...props} />
)
const GridEmptySpace = withTheme()(Presentation)
export default GridEmptySpace
<Grid item container xs={12} spacing={16}>
<Grid item xs={12} sm={6}>1</Grid>
<Grid item xs={12} sm={6}>2</Grid>
<GridEmptySpace
xs="hidden"
md={6}
xl="hidden"
/>
<Grid item xs={12} sm={6} md={3} xl={6}>3</Grid>
<Grid item xs={12} sm={6} md={3} xl={6}>3</Grid>
</Grid>
xs (empty space hidden)
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]
sm (empty space still hidden)
[ 1 ][ 2 ]
[ 3 ][ 4 ]
md & lg (empty space in bottom left)
[ 1 ][ 2 ]
[3] [4]
xl (hidden again)
[ 1 ][ 2 ]
[ 3 ][ 4 ]
@davnicwil

This comment has been minimized.

Copy link
Owner Author

@davnicwil davnicwil commented Jun 19, 2019

Caveats

  • React will give warnings about prop types in development mode, since material-ui uses prop types for the xs, sm, md, lg, xl props and 'hidden' is not a valid value.

  • The above code isn't properly typed with TS - I've just used any everywhere to avoid errors. Since it's a leaf component that nothing else depends on, I am not concerned about this and it works fine for me, but probably with a little bit more effort this could be typed properly, if you feel it's worth it in your usecase.

  • I HAVE NOT ROBUSTLY TESTED THIS and it might not work in all usecases or particularly complex / nested grid layouts. It's working fine for me though, in straightforward usecases like the above example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment