reactjsmaterial-uiconditional-rendering

Mui conditional rendering of one component


I would like to set disableGutters for MUI Container when xs size.

So far I was only able to do it like so:

<Container disableGutters sx={{ display: { xs: 'block', md: 'none' } }}>
    ...lot of code
</Container>

<Container sx={{ display: { xs: 'none', md: 'block' } }}>
    ...lot of duplicit code
</Container>

But because there is a lot of duplicit code I don't feel good about this solution, so is there a better way?


Solution

  • What you can do is use the MUI breakpoints like this:

    In your component you should add:

    import { useMediaQuery, useTheme } from "@mui/material";
    

    inside de component:

    const theme = useTheme();
    const isExtraSmallSize =  useMediaQuery(theme.breakpoints.down("xs"));
    

    and then:

    <Container disableGutters={isExtraSmallSize ? true : false} sx={{ display: { xs: 'block', md: 'none' } }}>
        ...lot of code
    </Container>
    

    or what you can do is use isExtraSmallSize to create the conditional rendering you need

    A custom hook with theme and useMediaQuery is very useful, I recommend you to do it