Migrating to Styled-Components with global SASS variables in React

Variables play a very important role in .scss or .sass, but the functionality cannot be extended outside the file.

Instead, you have to create a separate .js file (For example: variable.js) and define all your variables as an object.


Pardon me if this is an old question but I thought I chip in on how I use CSS variables for both my .scss and styled-components when the need arises.

Basic Usage:

Declaring a global variable (preferably at _variables.scss)

:root {
    --primary-color: #fec85b;
}

Using the global property:

.button {
    background-color: var(--primary-color);
}

or

const Button = styled.button`
    background-color: var(--primary-color);
`;

Please pay attention to the double line --.


I wrote up an article about solving this very issue. https://medium.com/styled-components/getting-sassy-with-sass-styled-theme-9a375cfb78e8

Essentially, you can use the excellent sass-extract library along with sass-extract-loader and the sass-extract-js plugin to bring your global Sass variables into your app as a theme object.


I recommend using the ThemeProvider component. I'm also moving away from sass and towards styled components. The Theming with styled-components uses React's context api and is quite nice. Check out the this documentation Styled Components Theming.