component-variants v1.1.0
Component Variants
Why this package?
To style different variants of a single component has so far been a hassle. This package greatly simplifies the way you define and type your variants of a component, while it keeps you in the same control as you have with styled components. Just a simple addon to styled-components.
Installation
With yarn
yarn add component-variantsor with NPM
npm i component-variantsUsage
We will assume the following imports
import React from "react";
import styled, { css } from "styled-components";
import { componentVariants, Variants } from "component-variants";To express our variants on a certain option, we create a nested styling object where the first level is the option (size) and its children is the variants (small, medium, large).
const variants = componentVariants({
size: {
small: css`
padding: 0;
`,
medium: css`
padding: 2px;
`,
large: css`
padding: 10px;
`,
},
});To extract the typings required by the mixin, we utilize the provided typings helper, Variants.
type ButtonProps = Variants<typeof variants>;We can then use this styling object (variants) as a mixin in our styled-component (MyStyledButton). Not that we've added ButtonProps to our styled button, to allow the usage to pass in the required props.
const StyledButton = styled.button<ButtonProps>`
${variants}
`;
interface Props extends ButtonProps {}
export const Button: React.FC<Props> = ({ size }) => {
return <StyledButton size={size} />;
};Variants
Variants can be described with string, enum, number or a string-represented boolean.
String
{
size: {
small: css``;
}
}Enums
{
size: {
[MyEnum.Small]: css``
}
}#### Numbers
{
size: {
0: css``
}
}#### String-represented boolean
{
size: {
false: css``,
true: css``
}
}Theme
You can still utilize theme the same way as you are used to.
{
size: {
small: css`
background-color: ${props => props.theme.colors.white};
`,
}
}If you have not set up theme yet, please follow the instructions by (styled-components)https://styled-components.com/docs/advanced.
Syntax
componentVariants(styledObject)
Parameters
styledObject | required
{
option: {
variant: Interpolation
}
}option is a string that describes the option you want to style. For example size
variant can be either a string, enum, number or a string-represented boolean.
Interpolation is the styled-components interpolation type that supports all styling you are used to do within your styled components