Adding custom breakpoints to material ui with typescript

Viewed 2957

I know that in the createMuiTheme() function you are able to update the values of the breakpoints like so.

const theme = createMuiTheme({
  breakpoints: {
    values: {
      xs: 0,
      sm: 600,
      md: 960,
      lg: 1280,
      xl: 1920,
    },
  },
})

I also know that Material UI (relatively) recently changed it where you can add custom values for breakpoints.

  breakpoints: {
    values: {
      tablet: 640,
      laptop: 1024,
      desktop: 1280,
    },
  },
});

However, I am using Typescript and I can't get it to work by overriding the breakpoint values as they explain here:

declare module "@material-ui/core/styles/createBreakpoints"
{
  interface BreakpointOverrides
  {
    xs: false; // removes the `xs` breakpoint
    sm: false;
    md: false;
    lg: false;
    xl: false;
    tablet: true; // adds the `tablet` breakpoint
    laptop: true;
    desktop: true;
  }
}

and instead get this error Type '{ tablet: number; laptop: number; desktop: number; }' is not assignable to type 'BreakpointValues'. Object literal may only specify known properties, and 'tablet' does not exist in type 'BreakpointValues'.

Not sure what I am doing wrong? Any help would be appreciated.

2 Answers

I am working with typescript and breakpoints MaterialUI, I think you need to import and modify some interface as documentation says (https://material-ui.com/guides/typescript/#customization-of-theme). So for example I have a Theme.tsx like this:

import { createMuiTheme } from '@material-ui/core/styles'
import {BreakpointOverrides} from "@material-ui/core/styles/createBreakpoints"

declare module "@material-ui/core/styles/createBreakpoints" {
  interface BreakpointOverrides {
    xs: false; // removes the `xs` breakpoint
    sm: false;
    md: false;
    lg: false;
    xl: false;
    tablet: true; // adds the `tablet` breakpoint
    laptop: true;
    desktop: true;
  }
}


declare module '@material-ui/core/styles/createMuiTheme' {
  interface Theme {
    appDrawer: {
      width: React.CSSProperties['width']
      breakpoint: BreakpointOverrides
    }
  }
  // allow configuration using `createMuiTheme`
  interface ThemeOptions {
    appDrawer?: {
      width?: React.CSSProperties['width']
      breakpoint?: BreakpointOverrides
    }
  }
}
export const theme = createMuiTheme({
  breakpoints: {
    values: {
      tablet: 400,
      laptop: 900,
      desktop: 1200
    }
  },})

I found the problems is due to the version of material-ui. The 4.9.9 version of @material-ui/core would cause the error messages. When I update to 4.11.0, it work correctly.

Related