-
Notifications
You must be signed in to change notification settings - Fork 16
/
useResponsive.ts
53 lines (41 loc) · 1.25 KB
/
useResponsive.ts
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
// TODO(#323): remove on v6
import { useCallback, useEffect, useState } from 'react'
import SingletonListener from '../utils/dom/SingletonListener'
let CURRENT_WIDTH = 767 as number
export interface ResponsiveWidthShorthand {
minWidth?: number | string
maxWidth?: number | string
}
/** @deprecated use decentraland-ui/dist/components/Media/Media */
export default function useResponsive() {
const [width, setWidth] = useState(CURRENT_WIDTH)
useEffect(() => {
function updateWidth() {
const currentWidth = window.innerWidth
if (CURRENT_WIDTH !== currentWidth) {
CURRENT_WIDTH = currentWidth
}
if (width !== currentWidth) {
setWidth(currentWidth)
}
}
updateWidth()
const listener = SingletonListener.from(window)
listener.addEventListener('resize', updateWidth)
return () => {
listener.removeEventListener('resize', updateWidth)
}
}, [width])
return useCallback(
function responsive(limits: Partial<ResponsiveWidthShorthand> = {}) {
if (limits.minWidth !== undefined && width < limits.minWidth) {
return false
}
if (limits.maxWidth !== undefined && width > limits.maxWidth) {
return false
}
return true
},
[width]
)
}