Created
September 4, 2024 09:23
-
-
Save jaydeepw/c6a89a410556bdb99b899adc583ba270 to your computer and use it in GitHub Desktop.
useBreakpoint.js using MUI v5.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useTheme } from "@mui/material/styles"; // or @mui/joy/styles | |
import useMediaQuery from "@mui/material/useMediaQuery"; | |
/** | |
* 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 | |
*/ | |
export const useBreakpoint = () => { | |
const theme = useTheme(); | |
const keys = [...theme.breakpoints.keys]; | |
return ( | |
keys.reduce((output, key) => { | |
// eslint-disable-next-line react-hooks/rules-of-hooks | |
const matches = useMediaQuery(theme.breakpoints.up(key)); | |
return matches ? key : output; | |
}, null) ?? "unknown" | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment