Created
June 15, 2020 18:18
-
-
Save manuel-mauky/78fddc6c42f01e8345ef58bcc2a0b562 to your computer and use it in GitHub Desktop.
React-Hooks-Article: useMedia hook
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 React, { useEffect, useState } from "react" | |
const useMedia = (query: string): boolean => { | |
const [matches, setMatches] = useState(false) | |
useEffect(() => { | |
const queryObject = window.matchMedia(query) | |
setMatches(queryObject.matches) | |
const listener = (e: MediaQueryListEvent) => { | |
setMatches(e.matches) | |
} | |
queryObject.addEventListener("change", listener) | |
return () => { | |
queryObject.removeEventListener("change", listener) | |
} | |
}, [query]) | |
return matches | |
} | |
export const UseMediaExample = () => { | |
const matches = useMedia("(min-width: 600px)") | |
return ( | |
<> | |
<p>Width is above 600 px: {matches ? "true" : "false"}</p> | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment