How to add media queries in React Material UI components?

Sometimes, we want to add media queries in React Material UI components.

In this article, we’ll look at how to add media queries in React Material UI components.

How to add media queries in React Material UI components?

To add media queries in React Material UI components, we can call makeStyles with a function that takes the theme parameter.

Then we can get the breakpoints from theme and use them as properties for applying styles for different screen sizes.

For instance, we write:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  drawerWidth: {
    width: "50%",
    backgroundColor: "yellow",
    [theme.breakpoints.up(780)]: {
      width: "80%"
    }
  }
}));

export default function App() {
  const classes = useStyles();

  return <div className={classes.drawerWidth}>hello world</div>;
}

We add the drawerWidth class property into the object returned by the makeStyles callback.

And we set it to an object that has the theme.breakpoints.up(780) property.

We set the width to '80%' when the width of the screen is 780px or wider.

Otherwise, the width is set to '50%'.

Conclusion

To add media queries in React Material UI components, we can call makeStyles with a function that takes the theme parameter.

Then we can get the breakpoints from theme and use them as properties for applying styles for different screen sizes.