Variants
Styled Benefits provides an extremely straight-forward way to define variants.
First import variant:
import { variant } from 'styled-benefits'
Then use it as a normal selector in your styled component:
Variants work similarly to :hover or @media selectors if variant prop matches the function argument, corresponding style is selected.
Style based on component props
Styled Benefits includes more powerful tool to style components with properties. That is withProps function:
import { withProps } from 'styled-benefits'
If you want to just check for the existence of the property, pass its name as a string:
You can check multiple props as well:
Alternatives
There are plenty of libraries that "simplifies" styling components via props. For example; popular Styled Map:
Styled Map
const Box = styled.div`width: 100px;height: 100px;border-radius: 10px;background: ${styledMap`dark: #393E41;light: #44BBA4;`};`
It's pretty and has its use cases, but withProps from Styled Benefits is more powerful tool.
If you're using Styled System it introduces its variant:
Styled System
const Box = styled.div`width: 100px;height: 100px;border-radius: 10px;${variant({variants: {dark: {bg: '#393E41',},light: {bg: '#44BBA4',},},})};`
You can instantly see the difference between these approaches. Styled System is designed to work with style objects, while Styled Benefits works with tagged template literals:
Styled Benefits ๐
const Box = styled.div`width: 100px;height: 100px;border-radius: 10px;${variant('dark')} {background: #393e41;}${variant('light')} {background: #44bba4;}`