added useWidth hook
This commit is contained in:
parent
d49bbd9447
commit
ab4fd77471
1 changed files with 27 additions and 0 deletions
27
src/hooks/useWidth.ts
Normal file
27
src/hooks/useWidth.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import { Breakpoint, Theme, useTheme } from "@mui/material/styles";
|
||||||
|
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||||
|
|
||||||
|
type BreakpointOrNull = Breakpoint | null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 function useWidth() {
|
||||||
|
const theme: Theme = useTheme();
|
||||||
|
const keys: 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 && matches ? key : output;
|
||||||
|
}, null) || "xs"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// useWidth wrapper that just tells you if you're in a mobile view or not given a set or
|
||||||
|
// using a standard set of "mobile" breakpoints. The same warnings as useWidth apply.
|
||||||
|
export function useMobile() {
|
||||||
|
return useWidth() === "xs";
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue