Skip to content

Instantly share code, notes, and snippets.

@damien-mcmahon
Last active March 13, 2022 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damien-mcmahon/c0d91c241980cb2a4da5afc96e2522ec to your computer and use it in GitHub Desktop.
Save damien-mcmahon/c0d91c241980cb2a4da5afc96e2522ec to your computer and use it in GitHub Desktop.
Clean Styled Components
import { color } from './helpers';
import { theme } from './theme';
describe('Helpers', () => {
describe('color', () => {
it('retrieves a colour from the theme', () => {
expect(color('green')({theme})).toEqual('#00F')
});
});
describe.todo('spacing');
describe.todo('radius');
});
import get from 'lodash.get';
import { BorderRadiusKey, Theme } from './helpers';
type ThemeProp = {
theme: Theme
}
export const colour = (name: keyof Theme['Colours']) => ({theme}: ThemeProp) => get(theme.colours, name);
export const spacing = (multiplier: number) => ({theme}:ThemeProp) => `${get(theme,'spacingValue') * multiplier}px`;
export const radius = (size: BorderRadiusKey) => ({theme}: ThemeProp) => get(theme.radius, size)};
import React from 'react';
import styled from 'styled-components';
import { colour, radius, spacing } from './helpers';
const Wrapper = styled.div`
border: 1px solid ${color('green')};
padding: ${spacing(5)};
border-radius: ${radius('medium')};
`;
export const SomeComponent: React.FC = (
<Wrapper>
...
</Wrapper>
);
const colours = {
green: '#00F',
white: '#FFF',
orange: '#CC5500'
}
type ThemeColour = typeof color;
export type BorderRadiusKeys = 'small' | 'medium' | 'large';
type BorderRadius = Record<BorderRadiusKeys, string>;
export type Theme = {
colours: ThemeColour,
spacingValue: number,
radius: BorderRadius
}
const spacingValue = 4;
const radius = {
'small' : '4px',
'medium': '8px',
'large': '12px',
};
const theme: Theme = {
colours,
radius,
spacingValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment