Skip to content

Instantly share code, notes, and snippets.

View jepser's full-sized avatar

Jepser Bernardino jepser

View GitHub Profile
/**
* Call the styles factory for with the correct props for each media query
* @param {function} stylesGenerator function that generates the styles
*
* @returns {array} array of styles to be applied for the registered media queries
*/
export const generateResponsiveStyles = stylesGenerator => props =>
Object.keys(mediaqueries).reduce((rules, mq) => {
if (!props[mq]) return rules;
const BASE_PROPS = ['top', 'right', 'bottom', 'left']
// with this component:
<Spacer sm={{ bottom: 1, top: 2 }} md={{ bottom: 2, top: 1 }} sl={{ top: 1 }} />
const responsiveProps = generateResponsiveProps(props, BASE_PROPS)
// will generate this and remove sl because that's not in my media queries
{
sm: {
/**
* Generate a valid structure for responsive configuration for a component
* @param {object} props props received from the component
* @param {array} baseProps list of props to be validated
*
* @returns a structured object with the props for each media query
*/
export const generateResponsiveProps = (props, baseProps) => {
// from the breakpoints registered check which props exists
const shapedPropsWithMq = Object.keys(BREAKPOINTS).reduce(
const Root = styled.div`
//…
${mediaqueries.md`
//specific rules for this break point
`
`
const Spacer = ({
top, left, bottom, right, children, sm, md, lg, xl,
}) => {
return (
<Root
top={ top }
left={ left }
bottom={ bottom }
right={ right }
sm={sm}
// for base usage
<Spacer bottom={2} left={2}>cool component here</Spacer>
// for responsive usage
<Spacer md={{ bottom: 2, left: 2 }} left={1}>cool component here</Spacer>
<MatchMedia query={BREAKPOINTS.md}>
 { matches => matches ? <UseThis /> : <UseOther /> }
</MatchMedia>
const Spacer = ({
top, left, bottom, right, children,
}) => {
return (
<Root
top={ top }
left={ left }
bottom={ bottom }
right={ right }
>
import { Col } from 'super-library'
// either like this
<Col md={5} offsetMd={1} />
// or this
<Col md={{ size: 5, offset: 1 }} />
@jepser
jepser / responsive-styled-components.js
Last active May 18, 2019 16:11
Implementation of responsive styled components
// helpers.js
/**
* Generate a valid structure for responsive configuration for a component
* @param {object} props props received from the component
* @param {array} baseProps list of props to be validated
*
* @returns a structured object with the props for each media query
*/
export const generateResponsiveProps = (props, baseProps) => {
// from the breakpoints registered check which props exists