Created
May 26, 2020 14:25
-
-
Save wKovacs64/1f9fcd69a5ce7ca3f7a3189319b2390e to your computer and use it in GitHub Desktop.
CSS-in-JS Media Query Utility Function in TypeScript
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
const breakpointMap = { | |
// mobile-first, so there is no 'xs' for portrait phones | |
sm: 576, // landscape phones | |
md: 768, // tablets | |
lg: 992, // landscape tablets and desktops | |
xl: 1200, // extra large desktops | |
}; | |
type Breakpoints = typeof breakpointMap; | |
type BreakpointLabel = keyof Breakpoints; | |
type MediaQueries = { [BL in BreakpointLabel]: string }; | |
export const mq: MediaQueries = (Object.entries(breakpointMap) as Array< | |
[BreakpointLabel, Breakpoints[BreakpointLabel]] | |
>).reduce<Partial<MediaQueries>>((accumulator, [label, bp]) => { | |
accumulator[label] = `@media (min-width: ${bp}px)`; | |
return accumulator; | |
}, {}) as MediaQueries; | |
// Usage example: | |
// | |
// css` | |
// color: 'white'; | |
// ${mq.md} { | |
// color: 'papaya'; | |
// } | |
// ` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment