Created
September 6, 2018 18:39
-
-
Save dgowrie/f80a5636e52e38f37ada4dd32361a51c to your computer and use it in GitHub Desktop.
Thin wrapper "macro" for declarative breakpoint media queries in emotion styled components
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
| /** | |
| * Similar to Sass mixins | |
| * Goals are: | |
| * - intuitive, sensible naming convention for ranges | |
| * - declarative syntax | |
| * Two approaches explored... | |
| */ | |
| /* Breakpoints - if we want to keep these as separate variables (pros/cons) */ | |
| const phone = '26.563em'; | |
| const tablet = '48.000em'; | |
| const desktop = '64em'; | |
| const breakpoints = { | |
| phone, | |
| tablet, | |
| desktop, | |
| }; | |
| /** | |
| * individual 'mixin' per MQ approach | |
| * is arguably easier to reason about and nicer to read | |
| */ | |
| function forTabletUp(styles) { | |
| return ` | |
| @media (min-width: ${breakpoints.tablet}) { | |
| ${styles} | |
| } | |
| `; | |
| } | |
| function forDesktopUp(styles) { | |
| return ` | |
| @media (min-width: ${breakpoints.desktop}) { | |
| ${styles} | |
| } | |
| `; | |
| } | |
| /** | |
| * alternative | |
| * pro: a single wrapper | |
| * con: requires mental mapping of these 'range' variables | |
| */ | |
| function forSize(range, styles) { | |
| switch (range) { | |
| case 'tablet-up': | |
| return ` | |
| @media (min-width: ${breakpoints.tablet}) { | |
| ${styles} | |
| } | |
| `; | |
| case 'desktop-up': | |
| return ` | |
| @media (min-width: ${breakpoints.desktop}) { | |
| ${styles} | |
| } | |
| `; | |
| default: | |
| return ''; | |
| } | |
| } | |
| /* usage of both approaches */ | |
| const StyledComponent = styled('div')` | |
| border: 1px solid red; | |
| ${forTabletUp(` | |
| background: yellow; | |
| `)} | |
| ${forDesktopUp(` | |
| background: green; | |
| `)} | |
| ${forSize('desktop-up', ` | |
| border-bottom: 3px dotted purple; | |
| `)} | |
| `; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment