Skip to content

Instantly share code, notes, and snippets.

@mieradi
Last active February 21, 2021 16:29
Show Gist options
  • Select an option

  • Save mieradi/7c94fd1d0a7eec8edef13c59a6377fdc to your computer and use it in GitHub Desktop.

Select an option

Save mieradi/7c94fd1d0a7eec8edef13c59a6377fdc to your computer and use it in GitHub Desktop.
/**
* @name mediaQuery
* @desc function to express media queries
* @param {string} size the size in which to invoke media query, represented in px
* @param {string} condition the condition in which to invoke media query. default is 'min'
* @returns returns desc
* @note the func param is to handle dynamic styles rendered by js rendered by a function
*/
import { css } from 'styled-components'
const sizes = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
xxl: 1536,
}
export const mediaQuery = (size: string, condition = 'min') => (
args: TemplateStringsArray,
...func: string[]
): string => {
return css`
@media (${condition}-width: ${sizes[size]}px) {
${css(...args, ...func)}
}
`
}
// You can use this in a Styled Component like this:
import { mediaQuery } from 'your/path/mediaQueries'
import { handleBackgroundColorExample } from 'your/path/helperFunctions'
const ExampleStyledComponent = styled.div`
// ...your styles
// without condition this will default to min-width
${mediaQuery('md')`
background-color: #ebebeb;
`}
// with condition will render max-width
${mediaQuery('md', 'max')`
background-color: ${handleBackgroundColorExample('#ebebeb')};
`}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment