Search code examples
javascriptreactjsmaterial-uifrontend

get current Material UI breakpoint name


I'm searching a MUI function " MaterialUIGiveMeCurrentBreakPointName" that allows me to performe an action in a component like this:

const currentBreakPointName = MaterialUIGiveMeCurrentBreakPointName()

if(currentBreakPointName === 'myCustomBreakPointName') {
  // do stuff 
}

Could you help me out please ?


Solution

  • Currently there is no such function available which will return you the current breakpoint name but you can achieve this using useMediaQuery hook.
    Refer : https://mui.com/material-ui/react-use-media-query/
    Working codesandbox : https://codesandbox.io/s/themehelper-demo-material-ui-forked-h2grmr?file=/demo.tsx

    const theme = useTheme();
    const greaterThanMid = useMediaQuery(theme.breakpoints.up("md"));
    const smallToMid = useMediaQuery(theme.breakpoints.between("sm", "md"));
    const lessThanSmall = useMediaQuery(theme.breakpoints.down("sm"));
    if (greaterThanMid) {
      console.log("Greater than mid");
    } else if (smallToMid) {
      console.log("Between small to mid");
    } else if (lessThanSmall) {
      console.log("Less than small");
    }
    

    enter image description here