-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
MediaQuery.tsx
57 lines (49 loc) · 1.82 KB
/
MediaQuery.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as React from 'react'
import { MediaQuery as MediaQueryParams } from '@const/defaultOptions'
import { joinQueryList } from '@utils/styles/createMediaQuery'
import normalizeQuery from '@src/utils/styles/normalizeQuery'
import transformNumeric from '@utils/math/transformNumeric'
import compose from '@src/utils/functions/compose'
interface MediaQueryProps extends MediaQueryParams {
children: (matches: boolean) => JSX.Element
matches?: boolean
}
const createMediaQuery = (queryParams: MediaQueryParams): string => {
return compose(
joinQueryList(([paramName, paramValue]) => {
/**
* Transform values that begin with a number to prevent
* transformations of "calc" expressions.
* Transformation of numerics is necessary when a simple
* number is used as a value (min-width: 750) is not valid.
*
* (min-width: 750) ==> (min-width: 750px)
*/
const resolvedParamValue = /^\d/.test(String(paramValue))
? transformNumeric(paramValue)
: paramValue
return `(${paramName}:${resolvedParamValue})`
}),
normalizeQuery,
)(queryParams)
}
const MediaQuery: React.FC<MediaQueryProps> = (props) => {
const { children, ...queryParams } = props
const query = React.useMemo(() => createMediaQuery(queryParams), [
queryParams,
])
const [matches, setMatches] = React.useState(false)
const handleMediaQueryChange = (
mediaQueryList: MediaQueryList | MediaQueryListEvent,
) => {
setMatches(mediaQueryList.matches)
}
React.useEffect(() => {
const mediaQueryList = matchMedia(query)
handleMediaQueryChange(mediaQueryList)
mediaQueryList.addListener(handleMediaQueryChange)
return () => mediaQueryList.removeListener(handleMediaQueryChange)
}, Object.keys(queryParams))
return children(matches)
}
export default MediaQuery