Files
react/pages/en-us/components/use-media-query.mdx
2020-05-16 23:05:11 +08:00

90 lines
2.3 KiB
Plaintext

import { Layout, Playground, Attributes } from 'lib/components'
import { useMediaQuery, Link, Code, Spacer } from 'components'
import NextLink from 'next/link'
import PlaygroundTitle from 'lib/components/playground/title'
export const meta = {
title: 'use-media-query',
group: 'Utils',
}
## Use MediaQuery
CSS media query hooks, it is implemented through the `MediaQuery` API.
If you just want to build the layout, try <NextLink href="/en-us/components/grid"><Link color>Grid Component</Link></NextLink>.
This is custom React Hooks, you need to follow the <Link target="_blank" color href="https://reactjs.org/docs/hooks-rules.html">Basic Rules</Link> when you use it.
<Playground
scope={{ useMediaQuery, Code }}
code={`
() => {
const isXS = useMediaQuery('xs')
const isSM = useMediaQuery('sm')
const isMD = useMediaQuery('md')
const isLG = useMediaQuery('lg')
const isXL = useMediaQuery('xl')
return (
<>
MediaQuery match: <Code>{isXS && 'xs'}{isSM && 'sm'}{isMD && 'md'}{isLG && 'lg'}{isXL && 'xl'}</Code>.
</>
)
}
`} />
<Playground
title="Match Type"
desc="You can choose to match up or down."
scope={{ useMediaQuery, Code }}
code={`
() => {
const upMD = useMediaQuery('md', { match: 'up' })
return (
<>
Current screen width <b>{upMD ? '>=' : '<='}</b> <Code>md</Code>.
</>
)
}
`} />
<PlaygroundTitle title="custom breakpoints" desc="Override the default breakpoints of the `@zeit-ui/react`." />
```tsx
const breakpoints: ZeitUIThemesBreakpoints = {
xs: { min: '0', max: '650px' },
sm: { min: '650px', max: '900px' },
md: { min: '900px', max: '1280px' },
lg: { min: '1280px', max: '1920px' },
xl: { min: '1920px', max: '10000px' },
}
const App = () => (
<ZeitProvider theme={{ breakpoints: breakpoints }}>
<CssBaseline />
<AppComponent />
</ZeitProvider>
)
```
<Attributes edit="/pages/en-us/components/use-media-query.mdx">
<Attributes.Title>useMediaQuery</Attributes.Title>
```ts
type ResponsiveBreakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'mobile'
type ResponsiveOptions = {
match?: 'up'| 'down',
ssrMatchMedia?: (query: string) => { matches: boolean }
}
const useMediaQuery = (
breakpoint: ResponsiveBreakpoint,
options?: ResponsiveOptions,
) => boolean
```
</Attributes>
export default ({ children }) => <Layout meta={meta}>{children}</Layout>