I am learning to create a website using Material-ui and React.
I want to create a collapsable grid where some rows are collapsed/expanded based on the state of page.
When I add a collapse component in the Grid layout, the Grid layout is broken.
I created a sample code here ( https://codesandbox.io/embed/jolly-golick-3lwt5) for demonstration.
Here, you see the collapsed part (where current condition is 'expanded' is not showing as expected.
Am I doing something wrong here?
This is much simpler but only shows the collapse-in animation.
<Grid item xs={3} style={{ display: showCollapse ? "block" : "none" }}>
<Collapse in={showCollapse}>
<Button>Button</Button>
</Collapse>
</Grid>
This right here worked for me:
import MuiCollapse from '@material-ui/core/Collapse'
import Grid from '@material-ui/core/Grid'
const GridItemXs12 = (props) => <Grid item xs={12} {...props} />
const Collapse = (props) => {
const classes = useCollapseStyles()
return (
<MuiCollapse
component={GridItemXs12}
classes={{
hidden: classes.hidden,
}}
{...props}
>
{/* This spacing has to match with the one in the container
outside the collapse */}
<Grid container spacing={2}>
{props.children}
</Grid>
</MuiCollapse>
)
}
const useCollapseStyles = makeStyles({
hidden: {
// The grid item's padding normally balances with the negative padding
// of the container outside the Collapse.
// But when the collapse hides its content, the padding of the item
// is still taking up space, creating an unwanted space.
// The 'hidden' style rule is only applied when the collapse finishes
// hiding its content
padding: '0 !important',
},
})
Then use this custom Collapse as a direct descendant of a Grid container
const MyComponent = () => {
return (
<Grid container spacing={2}>
<Collapse in={/* your controlled variable */}>
<Grid item xs={12}>
The content inside this grid item looks as if the item were
directly inside the container
</Grid>
</Collapse>
</Grid>
)
}
Here is a modified version of your sample code using this approach https://codesandbox.io/s/exciting-hodgkin-rk2wv, I added an onClick handler to the main div so that clicking anywhere within it toggles the collapse.
This solution assumes that you want to collapse something taking up the full width of your container. It also assumes that you want some spacing in that container (actually, without the spacing the grid doesn't break at all). Also, there is some jank in the animation when the padding style gets applied, the more the spacing, the more noticeable it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With