简体   繁体   中英

Using useMediaQuery in material ui?

So after building the complete web application, I've decided to make it mobile friendly. I'm using material ui framework with react. I read the documentation but am not sure as 2 how to use it. So let me give you an overview of what I think how to work it

Say I have this component

function App() {
  const matches = useMediaQuery(theme.breakpoints.down('sm'));
  return (
    <Button variant="contained" color="primary">
    </Button>
  );
}

So if I wanna apply styles to button as per the breakpoint(in this case 'sm'), I'd do something like this:

...
<Button styles={{matches? mobileBtn : desktopBtn}}>
...

assumming I have defined mobileBtn and desktopBtn .

Is this the correct approach to use it, or is there some other standard way to do so. Although I don't think there is because if there was it would be included in the documentation.

If I understand your question correctly, there is a built-in breakpoints mechanizm in makeStyles so you don't need useMediaQuery if you only want to change styles.

For example:

const useStyles = makeStyles((theme) => ({
  button: {
    padding: 8,
    backgroundColor: 'green',

    [theme.breakpoints.down('sm')]: {
      backgroundColor: 'red'
    },
  },
}));

function App() {
  const classes = useStyles();
  return (
    <Button variant="contained" className={classes.button}>
      Hello World
    </Button>
  );
}

https://codesandbox.io/s/restless-night-4zn76?file=/index.js

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