简体   繁体   中英

Material UI useMediaQuery causes glitching/jumping

I am using Material UI's useMediaQuery() hook, I have injected the theme provider and have created a variable like this:

const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down('sm') );

I'm using the isSmall variable in several places to determine various characteristics of my page. Here is an example:

<Typography variant={isSmall ? "body2" : "h5"}>
  Case Studies
</Typography>

The problem I am having is that when the page first loads it renders all of the false versions of isSmall and then quickly corrects it's self causing a rather unsightly glitch.

If I remove the useMediaQuery dependancies and set the styling using the makeStyles() method everything is fine, for example:

const useStyles = makeStyles((theme) => ({
  cardImg: {
    opacity: 0.8,
    height: '60px',
    [theme.breakpoints.down("sm")]: {
      height: '40px'
    }
  }
}));

This works fine but I don't see how I can invoke MUI style variables/variants like 'body2' and 'caption' etc without useMediaQueries.

If anyone can help I'd be appreciative.

Thanks, Dan.

I found a solution to this problem. It looks like I was experiencing this issue: https://github.com/mui-org/material-ui/issues/21048

The solution is to use the noSsr option (as I am not server-side rendering) like this:

const isSmall = useMediaQuery(theme.breakpoints.down('sm'), {noSsr: true});

It does actually mention this in the useMediaQuery API docs .

Thanks for your help,

Dan.

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