Variants

The variant utility from @xstyled/system makes variant based components easy to create.

Without variant utility

Variant are supported out of the box by styled-components. Let's create a button with two variants:

const Button = styled.button`
${p => !p.variant || p.variant === 'primary' && css`
color: red;
`}
${p => p.variant === 'secondary' && css`
color: blue;
`}
`
<Button variant="secondary" />

As you can see the code is kind of messy. The variant utility will help you to fix that.

With variant utility

The variant utility handles all complexity for you:

import { variant } from '@xstyled/system'
const Button = styled.button`
${variant({
default: 'primary',
variants: {
primary: css`
color: red;
`,
secondary: css`
color: blue;
`
}
})}
`
<Button variant="secondary" />

As you can see the code is cleaner, adding a variant is easy!

Use another prop

variant are useful for a lot of things, for example, the button could also have different sizes.

import { variant } from '@xstyled/system'
const sizeVariants = variant({
default: 'md',
prop: 'size',
variants: {
md: css`
padding: 8px;
`,
lg: css`
padding: 16px;
`
}
})
const Button = styled.button`
${sizeVariants}
`
<Button size="md" />

Read variants from the theme

Sometimes, you may want to specify variants in your theme. The key option gives you that possibility:

import { variant } from '@xstyled/system'
const Button = styled.button`
${variant({
key: 'buttons',
default: 'primary',
})}
`

In your theme:

// theme.js
export default {
buttons: {
primary: css`
color: red;
`,
secondary: css`
color: blue;
`,
},
}

All your variants are read from your theme!