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
- Install
node-sass
as a dependency or dev dependency - No need to do any config change in webpack
- 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);}
If you don't want to use styled-component
then you can follow this link.https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript
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.