Last active
January 30, 2021 20:33
-
-
Save ericp3reira/83726143b8745800c59064afe2c83280 to your computer and use it in GitHub Desktop.
Simple media query helper using TS and Styled Components, inspired by @morajabi's styled-media-query lib
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
// Inspired by https://github.com/morajabi/styled-media-query | |
// use: | |
/* | |
const MyComponent = styled.div` | |
${media.lessThan('mobile')` | |
background-color: red; | |
border: 2px solid black; | |
`} | |
${media.between('mobile', 'tablet')` | |
background-color: blue; | |
border: 2px solid red; | |
`} | |
` | |
*/ | |
import { css, FlattenSimpleInterpolation } from 'styled-components' | |
const breakpoints = { | |
mobile: '450px', | |
tablet: '768px', | |
desktop: '1170px', | |
desktop2k: '1440px' | |
} | |
const flattenTemplateStringArray = ( | |
args: TemplateStringsArray, | |
rest: string[] | |
) => | |
args.reduce((acc, item, index) => { | |
let str = acc + item | |
if (rest[index]) str += rest[index] | |
return str | |
}, '') | |
type MediaSizes = 'mobile' | 'tablet' | 'desktop' | 'desktop2k' | |
type MediaReturn = ( | |
args: TemplateStringsArray, | |
...rest: string[] | |
) => FlattenSimpleInterpolation | |
const lessThan = (size: MediaSizes): MediaReturn => { | |
return (args, ...rest) => css` | |
@media (max-width: ${breakpoints[size]}) { | |
${flattenTemplateStringArray(args, rest)} | |
} | |
` | |
} | |
const greaterThan = (size: MediaSizes): MediaReturn => { | |
return (args, ...rest) => css` | |
@media (min-width: ${breakpoints[size]}) { | |
${flattenTemplateStringArray(args, rest)} | |
} | |
` | |
} | |
const between = (lower: MediaSizes, higher: MediaSizes): MediaReturn => { | |
return (args, ...rest) => css` | |
@media (min-width: ${breakpoints[lower]}) and (max-width: ${breakpoints[ | |
higher | |
]}) { | |
${flattenTemplateStringArray(args, rest)} | |
} | |
` | |
} | |
const media = { | |
lessThan, | |
greaterThan, | |
between | |
} | |
export default media |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment