CSS variable with Styled Components

Since I’m working with Next.js and Styled-components (also TypeScript, React, GraphQL, Apollo, Storybook & Storyblok CMS) I was wondering, is it possible to use CSS variable’s in Styled Components.
import React, { Component } from 'react'
import styled from 'styled-components'
const CSSVariables = styled.div`
--color: ${props => props.color};
`
const Heading = styled.h1`
margin: 2rem 0 0 0;
color: var(--color);
`
const SingleStep = (props: Istep) => {
return (
<CSSVariables>
<Heading>My Heading</Heading>
</CSSVariables>
)
// All component logic
}
As you can see in the example above, it is possible and super simple, just like in normal CSS. So make sure that you CSS variable are created in a parent component. It can also be created on a page/layout level if you like.
So I hope this helps you further with building a cool Next.js or React application with Styled-components.
Thanks!
After reading this post, I hope you learned something new or are inspired to create something new! 🤗
If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM’s are always open 😁
Suggestions
Improve React Components With Optional Chaining & Nullish Coalescing
If you’re working on a big React (Next.js) application, sometimes you might need to dive deep into a data structure. Let's use Optional Chaining & Nullish Coalescing to improve React components.
Polished.js: A Utility CSS-in-JS library for Styled-Components in React.js
Sass functions like lighten(), darken(), complement(), invert() are pretty useful. I was wondering if there was something for styled-components. Well, I found the great library Polished.js.
How To Add Props To Styled Components in React.js with TypeScript
I’m pleased with Styled-components. Adding proper TypeScript typings was a big question for me, until now! So I want to share them with you. 😉