Created
June 13, 2017 02:12
-
-
Save souporserious/372cc6431a538fdfe9d5bcd539a51366 to your computer and use it in GitHub Desktop.
React space component for padding and margin
This file contains hidden or 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' | |
const BASE = 8 | |
const SIDES = ['Top', 'Right', 'Bottom', 'Left'] | |
const SIDES_LOWERCASE = ['top', 'right', 'bottom', 'left'] | |
function isNullLike(value) { | |
return value === null || typeof value === 'undefined' | |
} | |
function normalizeSpace( | |
{ all, horizontal, vertical, top, right, bottom, left } = {} | |
) { | |
const space = { | |
top: 0, | |
right: 0, | |
bottom: 0, | |
left: 0, | |
} | |
if (!isNullLike(all)) { | |
space.top = all | |
space.right = all | |
space.bottom = all | |
space.left = all | |
} | |
if (!isNullLike(horizontal)) { | |
space.right = horizontal | |
space.left = horizontal | |
} | |
if (!isNullLike(vertical)) { | |
space.top = vertical | |
space.bottom = vertical | |
} | |
if (!isNullLike(top)) { | |
space.top = top | |
} | |
if (!isNullLike(right)) { | |
space.right = right | |
} | |
if (!isNullLike(bottom)) { | |
space.bottom = bottom | |
} | |
if (!isNullLike(left)) { | |
space.left = left | |
} | |
return space | |
} | |
function Spacer({ tag = 'div', padding, margin, ...props }) { | |
const paddingSpace = normalizeSpace(padding) | |
const paddingStyles = SIDES_LOWERCASE.reduce( | |
(acc, side, index) => ({ | |
...acc, | |
[`padding${SIDES[index]}`]: paddingSpace[side] * BASE, | |
}), | |
{} | |
) | |
const marginSpace = normalizeSpace(margin) | |
const marginStyles = SIDES_LOWERCASE.reduce( | |
(acc, side, index) => ({ | |
...acc, | |
[`margin${SIDES[index]}`]: marginSpace[side] * BASE, | |
}), | |
{} | |
) | |
return React.createElement(tag, { | |
...props, | |
style: { ...paddingStyles, ...marginStyles }, | |
}) | |
} | |
export { Spacer as default, BASE } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment