-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseBreakpoint.ts
49 lines (42 loc) · 1.46 KB
/
useBreakpoint.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
import create, {
useIsomorphicEffect,
} from "@kodingdotninja/use-tailwind-breakpoint"
import resolveConfig from "tailwindcss/resolveConfig"
import tailwindConfig from "@/tailwind.config.js"
import { useRef, useState } from "react"
const config = resolveConfig(tailwindConfig)
if (!config.theme) throw new Error("No theme found in tailwind config")
// https://github.com/kodingdotninja/use-tailwind-breakpoint/blob/main/src/index.ts
export function useBreakpoint(
breakpoint: string,
defaultValue: boolean = false
) {
const [match, setMatch] = useState(() => defaultValue)
const matchRef = useRef(defaultValue)
useIsomorphicEffect(() => {
if (!(typeof window !== undefined && "matchMedia" in window))
return undefined
function track() {
if (!config?.theme?.screens) {
throw new Error("No screens found in Tailwind config")
}
if (
Array.isArray(config.theme.screens) ||
!config.theme.screens[breakpoint]
) {
throw new Error(`No screen found for ${breakpoint}`)
}
const value = config.theme.screens[breakpoint] ?? "999999px"
const query = window.matchMedia(`(min-width: ${value})`)
matchRef.current = query.matches
console.log(query.matches, breakpoint)
if (matchRef.current != match) {
setMatch(matchRef.current)
}
}
track()
window.addEventListener("resize", track)
return () => window.removeEventListener("resize", track)
})
return match
}