Created
June 20, 2020 15:24
-
-
Save petamoriken/e2160be246cb4aa820883fe453c8588c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
/** | |
* @example | |
* const matches = useMatchMedia("screen and (min-width: 560px)"); | |
* | |
* @param raw | |
*/ | |
export function useMatchMedia(raw: string): boolean { | |
const [matches, setMatches] = useState(false); | |
useEffect(() => { | |
// eslint-disable-next-line no-undef | |
const query = matchMedia(raw); | |
setMatches(query.matches); | |
const handleChange = (e: MediaQueryListEvent): void => { | |
setMatches(e.matches); | |
}; | |
// eslint-disable-next-line no-undef | |
if (query instanceof EventTarget) { | |
query.addEventListener("change", handleChange); | |
} else { | |
(query as MediaQueryList).addListener(handleChange); | |
} | |
return (): void => { | |
// eslint-disable-next-line no-undef | |
if (query instanceof EventTarget) { | |
query.removeEventListener("change", handleChange); | |
} else { | |
(query as MediaQueryList).removeListener(handleChange); | |
} | |
}; | |
}, [raw]); | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment