Last active
April 7, 2023 01:34
-
-
Save doubleedesign/b53af9d8c66c53eb909279637124e544 to your computer and use it in GitHub Desktop.
Typing styled-components props: Valid string values according to what's available in theme
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 styled from 'styled-components'; | |
import { ThemeColor } from '../../types'; | |
interface ButtonProps { | |
color: ThemeColor | |
} | |
export const StyledButton = styled.button<ButtonProps>` | |
background: ${({ theme, color }): string => theme.colors[color]}; | |
// more styles | |
&:hover, &:focus, &:active { | |
// Styles | |
}; | |
` |
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
export const theme = { | |
colors: { | |
primary: '#B48FFF', | |
secondary: '#87D9FF', | |
accent: '#9EFFC1' | |
}, | |
// ... More theme settings | |
} |
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 { theme } from './theme'; | |
// in this example, ThemeColor is equivalent to "primary" | "secondary" | "accent", | |
// but if we add another colour to the theme.colors object, it automatically becomes available to every styled-component using this type | |
export type ThemeColor = keyof typeof theme.colors; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment