Skip to content

Instantly share code, notes, and snippets.

@themojilla
Created August 23, 2021 19:14
Show Gist options
  • Save themojilla/e333c24047d6fd13b87da18e95a261f9 to your computer and use it in GitHub Desktop.
Save themojilla/e333c24047d6fd13b87da18e95a261f9 to your computer and use it in GitHub Desktop.
Spacer component for projects using Tailwind
// Based on: https://kyleshevlin.com/snippets/spacer
// PurgeCSS will remove the Tailwind margin classes from a production build.
// In order to keep them, you can safelist them via: https://tailwindcss.com/docs/optimizing-for-production#purge-css-options
type Margin = number | string;
type Margins = {
readonly top?: Margin;
readonly right?: Margin;
readonly bottom?: Margin;
readonly left?: Margin;
};
type SpacerProps = {
children: React.ReactNode;
all?: Margin;
horz?: Margin;
vert?: Margin;
top?: Margin;
right?: Margin;
bottom?: Margin;
left?: Margin;
};
export function Spacer({
children,
all = 0,
horz = 0,
vert = 0,
top = 0,
right = 0,
bottom = 0,
left = 0,
}: SpacerProps) {
const margins: Margins = {
...(all && {
top: all,
right: all,
bottom: all,
left: all,
}),
...(horz && {
left: horz,
right: horz,
}),
...(vert && {
top: vert,
bottom: vert,
}),
...(top && { top: top }),
...(right && { right: right }),
...(bottom && { bottom: bottom }),
...(left && { left: left }),
};
return (
<div
className={
` mt-${margins.top ?? 0}` +
` mr-${margins.right ?? 0}` +
` mb-${margins.bottom ?? 0}` +
` ml-${margins.left ?? 0}`
}
>
{children}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment