Tips: CSS Variables for styled-components

terrierscript

terrierscript

Posted on November 27, 2019

Tips: CSS Variables for styled-components

In styled-components, custom property can use with props

const Item = styled.div`
  color: ${({color}) => color};
  background: ${({bgCbolor = "red"}) => bgColor};
`
Enter fullscreen mode Exit fullscreen mode

but this syntax is redundant.

Solution: use CSS Variables

In modern browser, we can use CSS Variable. It’s very useful.

I found more useful that convert react props to CSS Variables.

export const Vars = styled.div`
  ${(props) => {
    return Object.entries(props)
      .filter(([_, v]) => typeof v === "string" || typeof v === "number")
      .map(([k, v]) => `--${k}: ${v};`)
      // You can convert to kebabCase if need.
      // .map(([k, v]) => `--${_.kebabCase(k)}: ${v};`)

  }}
`
Enter fullscreen mode Exit fullscreen mode

Usage


const Item = styled.div`
  color: var(β€”-color);
  background: var(β€”-bgColor, "blue");
`

const FooComponent = () => (
  <Vars color="red" bgColor="yellow">
    <Item />
  </Vars>
)
Enter fullscreen mode Exit fullscreen mode

Additionally, Be careful that variable effect to all component children. This behavior has pros and cons.

πŸ’– πŸ’ͺ πŸ™… 🚩
terrierscript
terrierscript

Posted on November 27, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Tips: CSS Variables for styled-components
javascript Tips: CSS Variables for styled-components

November 27, 2019