Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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

like image 190
Mosh Feu Avatar answered Dec 24 '25 05:12

Mosh Feu