Skip to content

Instantly share code, notes, and snippets.

@jaydeepw
Created September 4, 2024 09:23
Show Gist options
  • Save jaydeepw/c6a89a410556bdb99b899adc583ba270 to your computer and use it in GitHub Desktop.
Save jaydeepw/c6a89a410556bdb99b899adc583ba270 to your computer and use it in GitHub Desktop.
useBreakpoint.js using MUI v5.0
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