Last active
October 27, 2022 16:13
-
-
Save cassidoo/83e92e33cd09063c799a98199bb2ad75 to your computer and use it in GitHub Desktop.
An example of checking on a media query with React Hooks
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
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>) | |
} |
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
// Same thing as the other one, but more server-friendly instead of SPA stuff | |
function useMedia(query) { | |
const [matches, setMatches] = useState(false); | |
useEffect(() => { | |
const media = window.matchMedia(query); | |
if (media.matches !== matches) { | |
setMatches(media.matches); | |
} | |
const listener = () => { | |
setMatches(media.matches); | |
}; | |
media.addEventListener("change", listener); | |
return () => media.removeEventListener("change", listener); | |
}, [matches, query]); | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment