Last active
January 25, 2022 19:47
-
-
Save okmr-d/3496882873f0d48cb57153a65eed26ec to your computer and use it in GitHub Desktop.
useBreakpoints hooks (useMediaQuery を簡単に使えるようにしたやつ)
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 { useMediaQuery } from "./useMediaQuery" | |
const breakpoints = { | |
sm: 640, | |
md: 768, | |
lg: 1024, | |
xl: 1280, | |
"2xl": 1536, | |
} | |
type BreakpointKey = keyof typeof breakpoints | |
/** | |
* example: | |
* const isSmall = useBreakpoint("sm") // >= 640px | |
*/ | |
export const useBreakpoint = (key: BreakpointKey) => | |
useMediaQuery(`(min-width: ${breakpoints[key]}px)`) |
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 { useState, useEffect } from "react" | |
/** | |
* example: | |
* const isLargeOrMore = useMediaQuery("(min-width: 1024px)") | |
*/ | |
export const useMediaQuery = (query: string) => { | |
const [matches, setMatches] = useState( | |
typeof window === "undefined" ? false : window.matchMedia(query).matches | |
) | |
useEffect(() => { | |
const media = window.matchMedia(query) | |
if (media.matches !== matches) { | |
setMatches(media.matches) | |
} | |
const listener = () => setMatches(media.matches) | |
window.addEventListener("resize", listener) | |
return () => window.removeEventListener("resize", listener) | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, [query]) | |
return matches | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment