Last active
October 28, 2018 14:54
-
-
Save ljbc1994/50ce1b8467be29e2da98030199bd7c99 to your computer and use it in GitHub Desktop.
Styled Component Spacing Props Generation
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
import React from "react"; | |
import styled, { css } from "styled-components"; | |
const directions = { | |
T: "top", | |
L: "left", | |
R: "right", | |
B: "bottom" | |
}; | |
const boxModel = { | |
p: "padding", | |
m: "margin" | |
}; | |
const sizes = { | |
Xsm: "0.25rem", | |
Sm: "0.5rem", | |
Md: "1rem", | |
Lg: "1.5rem", | |
Xlg: "2rem" | |
}; | |
function handleProps(props) { | |
const passedProps = Object.keys(props); | |
const derivedProps = Object.keys(sizes).reduce((all, sizeName) => { | |
const size = sizes[sizeName]; | |
const sizeGroupedProps = {}; | |
Object.keys(directions).forEach((dir) => { | |
const direction = directions[dir]; | |
Object.keys(boxModel).forEach((bm) => { | |
const boxModelType = boxModel[bm]; | |
sizeGroupedProps[`${bm}${dir}${sizeName}`] = css` | |
${boxModelType}-${direction}: ${size}; | |
`; | |
}); | |
}); | |
return { ...all, ...sizeGroupedProps }; | |
}, {}); | |
return passedProps.map((p) => derivedProps[p]); | |
} | |
const Spacing = styled.div` | |
${handleProps} | |
`; | |
export default Spacing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment