How to use SCSS variables into my React components How to use SCSS variables into my React components reactjs reactjs

How to use SCSS variables into my React components


From React 17

To access your scss variables into the react component, you need to do something like that

  1. Install node-sass as a dependency or dev dependency
  2. No need to do any config change in webpack
  3. import as a module <-- main point

variables.module.scss

$color: skyblue;$primaryColor: red;:export {    color: $color;    primary-color: $primaryColor;}

App.js

import variables from '<YOUR_PATH>/variables.module.scss';const App = () => {    console.log(variables);}


There are different ways I can recomend you to tackle this.

1- Duplicate the values of those variables. Add them both on your variables.scss and as constants in some other file, maybe config.js or constants.js that way you'll be able to reference these values from your react components, the downside to this, is you'll have to remember to change them in two places if you have to modify the value.

2- Consider using styled-components. With styled components you can define your styles within your components, using variables or props within the styles.

3- Use some mechanism to define these variables in a single file or as environment variables, and setup your build process to be able to import these values into js and scss files.