Skip to content

Instantly share code, notes, and snippets.

@doubleedesign
Last active April 7, 2023 01:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Shortcut function for choosing text colour based on background colour using Styled Components + Polished
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';
}
}
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