Last active
April 7, 2023 01:33
-
-
Save doubleedesign/0588275dcbb63d16134ecff0ab19d8cd to your computer and use it in GitHub Desktop.
Shortcut function for choosing text colour based on background colour using Styled Components + Polished
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 { meetsContrastGuidelines } from 'polished'; | |
import { ContrastScores } from 'polished/lib/types/color'; | |
type WCAGLevel = keyof ContrastScores; | |
export function contrastTextColour(color: string, wcag: WCAGLevel = 'AA') { | |
const scores = meetsContrastGuidelines(color, '#fff'); | |
if(scores[wcag]) { | |
return '#fff'; | |
} | |
else { | |
return '#000'; | |
} | |
} |
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 { darken } from 'polished'; | |
import { ThemeColor } from '../../types'; | |
import { contrastTextColour } from '../../theme-utils'; | |
interface ButtonProps { | |
color: ThemeColor // See https://gist.github.com/doubleedesign/b53af9d8c66c53eb909279637124e544 for how this type works | |
} | |
export const StyledButton = styled.button<ButtonProps>` | |
background: ${({ theme, color }): string => theme.colors[color]}; | |
color: ${({ theme, color }): string => contrastTextColour(theme.colors[color])}; | |
text-decoration: underline; | |
text-decoration-color: transparent; | |
// ... more styles | |
&:hover, &:focus, &:active { | |
// theme.colors[color] may initially be "undefined" briefly when the component first loads, | |
// that's why there's a && conditional here | |
background: ${({ theme, color }): string => theme.colors[color] && darken(0.1, theme.colors[color])}; | |
}; | |
&:focus { | |
text-decoration-color: currentColor; | |
} | |
`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment