Migrating to Styled-Components with global SASS variables in React

I’m trying to slowly introduce Styled-Components into my existing codebase which relies heavily on global SASS variables (partials imported into a main.scss).

How do I reference the SCSS variables? The following doesn’t work:

import React from 'react';
import styled from 'styled-components';

const Button = styled.button`
  background-color: $color-blue;

export default Button;

Am I approaching this from the wrong way?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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);

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

Please pay attention to the double line --.

Method 3

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.

Method 4

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.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x