简体   繁体   中英

useMediaQuery to detect multiple breakpoints

I'm trying to detect multiple breakpoints on my application so that the columns generated on a Grid is dynamic. I'm able to achieve this but the code seems rather repetitive. Is there a way I can simplify my code further?

    const isMdUp = useMediaQuery(({ breakpoints }) => breakpoints.up('md'));
    const isSmUp = useMediaQuery(({ breakpoints }) => breakpoints.up('sm'));
    const isMdDown = useMediaQuery(({ breakpoints }) => breakpoints.down('md'));

    let imageListCol = 1;

    if (isMdUp) {
        imageListCol = 3;
    } else if (isSmUp && isMdDown) {
        imageListCol = 2;
    }
    
    return (
        <ImageList cols={imageListCol} gap={20}>
            ...
        </ImageList>
    )

Yes, you can remove one of them:

const isMdUp = useMediaQuery(({ breakpoints }) => breakpoints.up('md'));
const isSmUp = useMediaQuery(({ breakpoints }) => breakpoints.up('sm'));

// removing the isMdDown
// const isMdDown = useMediaQuery(({ breakpoints }) => breakpoints.down('md'));

let imageListCol = 1;

if (isMdUp) {
    imageListCol = 3;
} else if (isSmUp && !isMdUp) { // and we are going to use the opposite of isMdUp 
    imageListCol = 2;
}

return (
    <ImageList cols={imageListCol} gap={20}>
        ...
    </ImageList>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM