-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Lucas Silva
committed
Oct 7, 2019
1 parent
416b5f1
commit f5ab552
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 <span>{`width: ${width}`}</span>; | ||
} | ||
|
||
const theme = createMuiTheme(); | ||
|
||
export default function UseWidth() { | ||
return ( | ||
<ThemeProvider theme={theme}> | ||
<MyComponent /> | ||
</ThemeProvider> | ||
); | ||
} |