Solution

To use css variables in styled components, same as in CSS use --main-color with a variable name to create variables and use var function with variables name.

Snippet

In this snippet, we will import styled components library and create buttons using styled components, then create --main-color variables as a blue and use --main-color variables in button color using var function.

const Button = styled.div`
--main-color: blue;
color: var(--main-color);
&:hover {
  color: red; 
}

Example

In this example, we will create styled componets library and Button component has a custom property (--main-color) with a value of blue and variable color (--main-color) click on hover then change the color of red.

Let’s start coding…

App.js

import styled from 'styled-components';

const Button = styled.div`
--main-color: blue;
color: var(--main-color);
&:hover {
  color: red; 
}
`;

const Example1 = () => {
  return (
    <div>
      <Button>Normal</Button>
      <Button>Primary</Button>
    </div>
  );
};

export default Example1;

Output

variables

Here, we are provided code sandbox links for the above program variables in styled components. then you can use whenever you went and do the changes as per your requirements.

codesandbox

Happy Coding,

I hope the above example with help you to do your task.