Search code examples
reactjsmaterial-ui

Using customized breakpoints inside a theme in Mui


I've created a theme for my react app and customized the default mui breakpoints.
Now I'm trying to update the typography variants fontSize according to these customized breakpoints and not according to Mui default breakpoints, how can I do it?
Here's what I've tried:

import { createTheme } from "@mui/material/styles";

const breakpoints = {
  values: {
    xs: 0,
    sm: 576,
    md: 768,
    lg: 992,
  },
};

const theme = createTheme({
  breakpoints: breakpoints,
  typography: {
    fontSize: "2rem",
    h2: {
      [breakpoints.values.lg]: {
        fontSize: "4.25rem",
      },
    },
    h4: {
      fontSize: "1rem",
      [breakpoints.values.lg]: {
        fontSize: "2.125rem",
      },
    },
  },
});

export default theme;

without success.
If I try to change [breakpoints.values.lg] with [createTheme().breakpoints.up("lg")] that will use the default Mui breakpoint.


Solution

  • I was able to achieve it by doing the following:

    import { createTheme, ThemeOptions } from "@mui/material/styles";
    import { TypographyOptions } from "@mui/material/styles/createTypography";
    
    const breakpoints = {
      values: {
        xs: 0,
        sm: 576,
        md: 768,
        lg: 992,
        xl: 1200,
      },
    };
    
    export let theme = createTheme({
      typography: {
        fontFamily: ["Open Sans", "Roboto", "Nunito", "sans-serif"].join(", "),
        h2: {
          fontSize: "2rem",
          color: dark,
          fontWeight: 700,
        },
      } as ExtendedTypographyOptions,
      breakpoints: breakpoints,
    } as ThemeOptions);
    
    theme = createTheme({
      palette: {
        primary: {
          main: dark,
        },
        secondary: {
          main: blue,
        },
        error: {
          main: red,
        },
        success: {
          main: green,
        },
      },
      typography: {
        fontFamily: ["Open Sans", "Roboto", "Nunito", "sans-serif"].join(", "),
        htmlFontSize: 10,
        h1: {
          fontSize: "3.5rem",
          color: dark,
          fontWeight: 700,
        },
        h2: {
          fontSize: "2rem",
          color: dark,
          fontWeight: 600,
          [theme.breakpoints.up("md")]: {
            fontSize: "4.25rem",
          },
        },
        h3: {
          fontSize: "1rem",
          fontWeight: 500,
    
          [theme.breakpoints.up("md")]: {
            fontSize: "2.125rem",
          },
        },
      } as ExtendedTypographyOptions,
      breakpoints,
    } as ThemeOptions);
    

    I have used Typescript in my code in order to make the code fully typed. If you're not using Typescript, then you can just take out the types.