forked from Disciplr-Org/Disciplr-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseBreakpoint.ts
More file actions
45 lines (34 loc) · 1.17 KB
/
Copy pathuseBreakpoint.ts
File metadata and controls
45 lines (34 loc) · 1.17 KB
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
import { useEffect, useState } from 'react'
export const breakpoints = {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
} as const
export type Breakpoint = keyof typeof breakpoints
export function getBreakpointQuery(breakpoint: Breakpoint) {
return `(min-width: ${breakpoints[breakpoint]})`
}
function getInitialMatch(breakpoint: Breakpoint) {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return false
}
return window.matchMedia(getBreakpointQuery(breakpoint)).matches
}
export function useBreakpoint(breakpoint: Breakpoint) {
const [matches, setMatches] = useState(() => getInitialMatch(breakpoint))
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
setMatches(false)
return
}
const mediaQuery = window.matchMedia(getBreakpointQuery(breakpoint))
const syncMatch = (event?: MediaQueryListEvent) => {
setMatches(event ? event.matches : mediaQuery.matches)
}
syncMatch()
mediaQuery.addEventListener('change', syncMatch)
return () => mediaQuery.removeEventListener('change', syncMatch)
}, [breakpoint])
return matches
}