Ott 577 replace react responsive lib (#229)
* refactor(577): added useMediaQuery and removed react-responsive lib * feat(577): added MediaQuery component * refactor(577): replaced useMediaQuery hook usage to MediaQuery component * refactor(577): simplified useMediaQuery arg typekeep-around/af30b88d367751c9e05a735e4a0467a96238ef47
parent
0bdd1af5f5
commit
feb8f69b46
@ -0,0 +1,16 @@ |
||||
import type { MediaQueryConfig, Devices } from 'config' |
||||
import { devices as maxDevices } from 'config' |
||||
|
||||
const minDevices: MediaQueryConfig = { |
||||
desktop: '(min-width: 1281px)', |
||||
laptop: '(min-width: 1025px)', |
||||
large: '(min-width: 1900px)', |
||||
mobile: '(min-width: 0px)', |
||||
tablet: '(min-width: 641px)', |
||||
} |
||||
|
||||
export const getQuery = (maxDevice?: Devices, minDevice?: Devices) => { |
||||
if (maxDevice) return maxDevices[maxDevice] |
||||
if (minDevice) return minDevices[minDevice] |
||||
return '' |
||||
} |
||||
@ -0,0 +1,23 @@ |
||||
import { |
||||
useEffect, |
||||
useState, |
||||
useMemo, |
||||
} from 'react' |
||||
|
||||
export const useMediaQuery = (query: string) => { |
||||
const mediaQuery = useMemo(() => matchMedia(query), [query]) |
||||
const [queryMatches, setQueryMatches] = useState(mediaQuery.matches) |
||||
|
||||
useEffect(() => { |
||||
const listener = (event: MediaQueryListEvent) => { |
||||
setQueryMatches(event.matches) |
||||
} |
||||
mediaQuery.addEventListener('change', listener) |
||||
|
||||
return () => { |
||||
mediaQuery.removeEventListener('change', listener) |
||||
} |
||||
}, [mediaQuery]) |
||||
|
||||
return queryMatches |
||||
} |
||||
@ -1 +1,37 @@ |
||||
export * from 'react-responsive' |
||||
import type { ReactNode } from 'react' |
||||
import React, { Fragment } from 'react' |
||||
|
||||
import type { Devices } from 'config' |
||||
|
||||
import { getQuery } from './helpers' |
||||
import { useMediaQuery } from './hooks' |
||||
|
||||
export * from './hooks' |
||||
|
||||
type Props = { |
||||
children: ReactNode, |
||||
|
||||
/** работает так же, как медиа запрос (max-width: width) */ |
||||
maxDevice?: Devices, |
||||
|
||||
/** работает так же, как медиа запрос (min-width: width) */ |
||||
minDevice?: Devices, |
||||
} |
||||
|
||||
export const MediaQuery = ({ |
||||
children, |
||||
maxDevice, |
||||
minDevice, |
||||
}: Props) => { |
||||
const query = getQuery(maxDevice, minDevice) |
||||
const queryMatches = useMediaQuery(query) |
||||
return ( |
||||
<Fragment> |
||||
{ |
||||
queryMatches |
||||
? children |
||||
: null |
||||
} |
||||
</Fragment> |
||||
) |
||||
} |
||||
|
||||
Loading…
Reference in new issue