Created
February 16, 2022 14:05
-
-
Save isomorpheric/777898d425e9f837db035985dae1751e to your computer and use it in GitHub Desktop.
useTailwindMediaQuery.ts
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 { useEffect, useState } from 'react'; | |
interface ItwBreakpoints { | |
[key: string]: string; | |
} | |
// This is straight from default tailwind config. | |
// Would have loved to use resolveConfig but | |
// you try to get it to work with ts. | |
const twBreakpoints: ItwBreakpoints = { | |
sm: '640px', | |
md: '768px', | |
lg: '1024px', | |
xl: '1280px', | |
'2xl': '1536px', | |
}; | |
// Uses tailwinds breakpoints to consume media queries. | |
const useMediaQuery = (twBreakpoint: string) => { | |
const [matches, setMatches] = useState(false); | |
useEffect(() => { | |
const query = `(min-width: ${twBreakpoints[twBreakpoint]})`; | |
console.log('query is:', query); | |
const media = window.matchMedia(query); | |
if (media.matches !== matches) { | |
setMatches(media.matches); | |
} | |
const listener = () => { | |
setMatches(media.matches); | |
}; | |
window.addEventListener('resize', listener); | |
return () => { | |
console.log('RETURNING'); | |
window.removeEventListener('resize', listener); | |
}; | |
}, [matches, twBreakpoint]); | |
return matches; | |
}; | |
export default useMediaQuery; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment