@mantine/hooks
Version:
A collection of 50+ hooks for state and UI management
1 lines • 2.06 kB
Source Map (JSON)
{"version":3,"file":"use-media-query.mjs","names":[],"sources":["../../src/use-media-query/use-media-query.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\n\nexport interface UseMediaQueryOptions {\n getInitialValueInEffect: boolean;\n}\n\nfunction getInitialValue(query: string, initialValue?: boolean) {\n if (typeof initialValue === 'boolean') {\n return initialValue;\n }\n\n if (typeof window !== 'undefined' && 'matchMedia' in window) {\n return window.matchMedia(query).matches;\n }\n\n return false;\n}\n\nexport function useMediaQuery(\n query: string,\n initialValue?: boolean,\n { getInitialValueInEffect }: UseMediaQueryOptions = {\n getInitialValueInEffect: true,\n }\n): boolean {\n const [matches, setMatches] = useState(\n getInitialValueInEffect ? initialValue : getInitialValue(query)\n );\n useEffect(() => {\n try {\n if ('matchMedia' in window) {\n const mediaQuery = window.matchMedia(query);\n setMatches(mediaQuery.matches);\n const callback = (event: MediaQueryListEvent) => setMatches(event.matches);\n mediaQuery.addEventListener('change', callback);\n return () => {\n mediaQuery.removeEventListener('change', callback);\n };\n }\n } catch (e) {\n // Safari iframe compatibility issue\n return undefined;\n }\n }, [query]);\n\n return matches || false;\n}\n\nexport namespace useMediaQuery {\n export type Options = UseMediaQueryOptions;\n}\n"],"mappings":";;;AAMA,SAAS,gBAAgB,OAAe,cAAwB;CAC9D,IAAI,OAAO,iBAAiB,WAC1B,OAAO;CAGT,IAAI,OAAO,WAAW,eAAe,gBAAgB,QACnD,OAAO,OAAO,WAAW,KAAK,EAAE;CAGlC,OAAO;AACT;AAEA,SAAgB,cACd,OACA,cACA,EAAE,4BAAkD,EAClD,yBAAyB,KAC3B,GACS;CACT,MAAM,CAAC,SAAS,cAAc,SAC5B,0BAA0B,eAAe,gBAAgB,KAAK,CAChE;CACA,gBAAgB;EACd,IAAI;GACF,IAAI,gBAAgB,QAAQ;IAC1B,MAAM,aAAa,OAAO,WAAW,KAAK;IAC1C,WAAW,WAAW,OAAO;IAC7B,MAAM,YAAY,UAA+B,WAAW,MAAM,OAAO;IACzE,WAAW,iBAAiB,UAAU,QAAQ;IAC9C,aAAa;KACX,WAAW,oBAAoB,UAAU,QAAQ;IACnD;GACF;EACF,SAAS,GAAG;GAEV;EACF;CACF,GAAG,CAAC,KAAK,CAAC;CAEV,OAAO,WAAW;AACpB"}