Last active
March 13, 2022 14:59
-
-
Save damien-mcmahon/c0d91c241980cb2a4da5afc96e2522ec to your computer and use it in GitHub Desktop.
Clean Styled Components
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 { 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'); | |
}); |
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 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)}; |
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 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> | |
); |
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
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