Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 376
user345 Avatar asked Feb 18 '26 10:02

user345


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

like image 150
Rohan Veer Avatar answered Feb 19 '26 22:02

Rohan Veer


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()
like image 28
Alexandru Cancescu Avatar answered Feb 20 '26 00:02

Alexandru Cancescu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!