get current Material UI breakpoint name

Viewed 355

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 ?

2 Answers

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

Here's a custom hook that'd suit your needs.

import {
  Breakpoint,
  Theme,
  useMediaQuery,
  useTheme
} from '@mui/material/styles'

/**
 * taken from https://material-ui.com/components/use-media-query/#migrating-from-withwidth
 *
 * Be careful using this hook. It only works because the number of
 * breakpoints in theme is static. It will break once you change the number of
 * breakpoints. See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
 */
type BreakpointOrNull = Breakpoint | null

export const useWidth = (): Breakpoint => {
  const theme: Theme = useTheme()
  const keys: readonly Breakpoint[] = [...theme.breakpoints.keys].reverse()
  return (
    keys.reduce((output: BreakpointOrNull, key: Breakpoint) => {
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const matches = useMediaQuery(theme.breakpoints.up(key))
      return output != null && matches ? key : output
    }, null) ?? 'xs'
  )
}

Usage

const breakpoint = useWidth()
Related