Skip to content

Instantly share code, notes, and snippets.

@ljbc1994
Last active October 28, 2018 14:54
Show Gist options
  • Save ljbc1994/50ce1b8467be29e2da98030199bd7c99 to your computer and use it in GitHub Desktop.
Save ljbc1994/50ce1b8467be29e2da98030199bd7c99 to your computer and use it in GitHub Desktop.
Styled Component Spacing Props Generation
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