How to use breakpoints in Material UI

H
andrewgbliss
4 months ago

This article will cover how to use breakpoints in Material UI

. . .

Github repo

https://github.com/EntryLevelDeveloperTraining/todos

What is a breakpoint?

In CSS (Cascading Style Sheets) a breakpoint is used to adapt layouts and elements according to the screen size of the device you are using. On a mobile phone you have a small screen, a table you have a medium size, and a desktop monitor you have large screens.

With breakpoints you can change the CSS to adapt to these sizes. For instance if you have an input that has a size of 400 on a desktop and you view it on mobile it will go off the edge and wont look good. That is where we can use breakpoints to change the size depending on the screen size.

So on our text input on the last article we have this CSS:

const useStyles = makeStyles((theme) => ({
  textField: {
    width: 400,
  },
}));

This code will always have the text input to be a width of 400. You can see if you run this on a mobile device the input goes off of the page.

Let's change it to use a breakpoint.

Let's go to the Material UI website and checkout the different breakpoints we can use:

https://material-ui.com/customization/breakpoints/

Default breakpoints

Each breakpoint (a key) matches with a fixed screen width (a value):

  • xs, extra-small: 0px
  • sm, small: 600px
  • md, medium: 960px
  • lg, large: 1280px
  • xl, extra-large: 1920px

So on a mobile device we want to use the xs size. The code now looks like this:

const useStyles = makeStyles((theme) => ({
  textField: {
    width: 400,
    [theme.breakpoints.down("xs")]: {
      width: 200,
    },
  },
}));

This will say that when the screen size hits the xs breakpoint and anything below it will change the width to 200. Everything else will still be 400.

useMediaQuery

https://material-ui.com/components/use-media-query/

Now in our App component we want to change the way the grid shows the layout. On a mobile device we want to show the input at the top, however on everything else we want to show everything in the middle.

import { useTheme } from "@material-ui/core/styles";
import useMediaQuery from "@material-ui/core/useMediaQuery";

const theme = useTheme();  
const matches = useMediaQuery(theme.breakpoints.down("xs"));

So let's bring in the useTheme and useMediaQuery. This will bring in the theme and then when the screen goes below the xs breakpoint it will trigger the matches variable to be true. So now we can change the grid to this:

<Grid
      className={classes.root}
      container
      justify="center"
      alignItems={matches ? "flex-start" : "center"}
    >

Conclusion

So that's how to use breakpoints to style our components differently based on the screen size. You can change more than just width, you can hide or show elements and any CSS you want to change you can do using breakpoints.


H
andrewgbliss
4 months ago