diff --git a/docs/src/pages/components/use-media-query/UseWidth.tsx b/docs/src/pages/components/use-media-query/UseWidth.tsx new file mode 100644 index 00000000000000..8cd8e061a2799d --- /dev/null +++ b/docs/src/pages/components/use-media-query/UseWidth.tsx @@ -0,0 +1,38 @@ +import React from 'react'; +import { Theme, ThemeProvider, useTheme, createMuiTheme } from '@material-ui/core/styles'; +import useMediaQuery from '@material-ui/core/useMediaQuery'; +import { Breakpoint } from '@material-ui/core/styles/createBreakpoints'; + +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 + */ +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' + ); +} + +function MyComponent() { + const width = useWidth(); + return {`width: ${width}`}; +} + +const theme = createMuiTheme(); + +export default function UseWidth() { + return ( + + + + ); +}