Skip to content

Instantly share code, notes, and snippets.

@davnicwil
Last active June 19, 2019 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davnicwil/e4d18ab12b282c4c8d85b2c3ba8f7df7 to your computer and use it in GitHub Desktop.
Save davnicwil/e4d18ab12b282c4c8d85b2c3ba8f7df7 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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