DEV Community

terrierscript
terrierscript

Posted on

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.

Top comments (4)

Collapse
 
yaireo profile image
Yair Even Or • Edited

If the component (Item) already has the variables set, that they are of higher specificity than the wrapper's (Var), therefore, rendering the Var's variables ineffective.

Also, it has the undesired side-effect of having to wrap the DOM element using a div that its whole function is solely to have the variables as class. This method is dirty since you can achieve the same result without the unnecessary div wrapper element, but by simply adding another class, via Styled-components, which will only host the variables.

I've made an example:
codesandbox.io/s/styled-components...

Collapse
 
kinston profile image
Kinston

Is it possible to use CSS variables in React-Native? If not, is there a similar way to store variables in React-Native with Styled-Component?

Collapse
 
dance2die profile image
Sung M. Kim

Would using CSS variable prevent styled components (SC) generating classes per each CSS variable value?

e.g.) SC would generate 100 classes for 100 colors with props.

Collapse
 
terrierscript profile image
terrierscript

Maybe yes, component not generate classes but <Vars> components class is generated.
I'm not that right solution but it's maybe solve attrs.
styled-components.com/docs/basics#...