Last active
February 10, 2023 17:48
-
-
Save donaldpipowitch/b454bbfbc3c81a6708a915086cc0de31 to your computer and use it in GitHub Desktop.
useMatchMedia - a React hook for matchMedia / media queries
This file contains hidden or 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 { useState, useEffect } from 'react'; | |
// pass a query like `(min-width: 768px)` | |
export function useMatchMedia(query: string) { | |
const [matches, setMatches] = useState(() => matchMedia(query).matches); | |
useEffect(() => { | |
const mediaQueryList = matchMedia(query); | |
const onChange = (event: MediaQueryListEvent) => setMatches(event.matches); | |
// note 1: safari currently doesn't support add/removeEventListener so we use add/removeListener | |
// note 2: add/removeListener are maybe marked as deprecated, but that could be wrong | |
// see https://github.com/microsoft/TypeScript/issues/32210 | |
mediaQueryList.addListener(onChange); | |
return () => mediaQueryList.removeListener(onChange); | |
}, [query]); | |
return matches; | |
} |
While testing on safari i found out that addEventListener wasn't defined.
Perhaps this hook should use https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener instead
Oh yeah, absolutely. Thanks for the ping. I'll update the Gist with the version we currently use in production.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While testing on safari i found out that addEventListener wasn't defined.
Perhaps this hook should use https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener instead