-
-
Save whoisryosuke/ebce86fbe1c663703451e8eea198882e to your computer and use it in GitHub Desktop.
An example of checking on a media query with React Hooks
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
function useMedia(query) { | |
const [matches, setMatches] = useState(window.matchMedia(query).matches) | |
useEffect(() => { | |
const media = window.matchMedia(query) | |
if (media.matches !== matches) { | |
setMatches(media.matches) | |
} | |
const listener = () => { | |
setMatches(media.matches) | |
} | |
media.addEventListener(listener) | |
return () => media.removeEventListener(listener) | |
}, [matches, query]) | |
return matches | |
} | |
// Example usage: | |
function SomeComponent() { | |
let isWide = useMedia('(min-width: 800px)') | |
return (<div>The window is {isWide ? 'wide' : 'not wide'}</div>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment