get current Material UI breakpoint name
Asked Answered
E

6

12

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 ?

Edraedrea answered 1/7, 2022 at 8:15 Comment(0)
S
21

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

Scintilla answered 1/7, 2022 at 11:23 Comment(0)
P
3

For em @Apoplectic's answer was not working so I adapted it. It is still a custom hook.

import {Theme, useTheme } from '@mui/material/styles' // or @mui/joy/styles
import useMediaQuery from "@mui/material/useMediaQuery";
import {Breakpoint} from "@mui/system";

/**
 * 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]
    console.log(keys);
    return (
        keys.reduce((output: BreakpointOrNull, key: Breakpoint) => {
            // eslint-disable-next-line react-hooks/rules-of-hooks
            const matches = useMediaQuery(theme.breakpoints.up(key))
            return matches ? key : output
        }, null) ?? 'xs'
    )
}

Usage

const breakpoint = useWidth()
Profanatory answered 8/5, 2023 at 20:9 Comment(1)
This is problematic, better us something without calling hooks conditionallyReunite
G
1

A simple hook that will work with the default breakpoints of xs,sm,md,lg and xl. This hook works with material ui version 5.11.x. You could extend this with more functions relating to the breakpoint. For example when using with props instead of using props.size you could use props[getBreakPointName()].size for a responsive size value.

useBreakpoint.js Hook

import { useMediaQuery, useTheme } from "@mui/material";

/**
 * useBreakpoint
 * 
 * @returns 
 */
const useBreakpoint = () => {

/**
 * useTheme
 */
const theme = useTheme();

/**
 * useMediaQuery
 * 
 */
const mq_xs = useMediaQuery(theme.breakpoints.only('xs'));
const mq_sm = useMediaQuery(theme.breakpoints.only('sm'));
const mq_md = useMediaQuery(theme.breakpoints.only('md'));
const mq_lg = useMediaQuery(theme.breakpoints.only('lg'));
const mq_xl = useMediaQuery(theme.breakpoints.only('xl'));

/**
 * getBreakPointName
 * 
 */
const getBreakPointName = () => {

    if(mq_xs){
        return "xs"
    }
    if(mq_sm){
        return "sm"
    }
    if(mq_md){
        return "md"
    }
    if(mq_lg){
        return "lg"
    }
    if(mq_xl){
        return "xl"
    }

}

return {
    getBreakPointName
}
}

export default useBreakpoint 
Ginoginsberg answered 31/3, 2023 at 12:19 Comment(1)
This is the best version!Reunite
E
1

It work with this code, if dont want to use typescript just remove the types.

const theme = useTheme();

const keys: readonly Breakpoint[] = [...theme.breakpoints.keys].reverse();

return (
   keys.filter((key: Breakpoint) => {
       // eslint-disable-next-line react-hooks/rules-of-hooks
       const matches = useMediaQuery(theme.breakpoints.up(key));

       if (matches) return true;
       return false;
   }, null)[0] ?? "xs"
);
Eldridge answered 11/10, 2023 at 17:48 Comment(0)
C
1

Might be too late here, however this is what I use for such purposes:

const useBreakpoint = (): Breakpoint => {
  const theme = useTheme();
  const breakpoints = ['xs', 'sm', 'md', 'lg', 'xl'] as Breakpoint[];

  // the reason to use filter is that you should have same amount of hooks between renders
  // find will not work as you will call hooks till you get tru from useMediaQuery
  const [breakpoint] = breakpoints.filter((breakpoint) => useMediaQuery(theme.breakpoints.only(breakpoint))) as Breakpoint[];
  
  return breakpoint 
};
Cabalistic answered 4/7, 2024 at 19:14 Comment(0)
S
0

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()
Starrstarred answered 10/8, 2022 at 10:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.