React and SCSS export a variable from scss to react
Asked Answered
Z

2

0

i am trying to export a color from my .scss file to my React.

colors.scss

:root {
  --color2: #606060;
}

$color: #88b5dd;
$color2: var(--color2);

.export {
 color: $color
 color2: $color2
}

and reading it in my React:

App.js

import {Colors} from './colors.scss'
console.log(Colors.color)
console.log(Colors.color2)

and in the console.log i can see:

#88b5dd
var(--color2)

color2 is not a color, the var(--color2) doesn't get interpolated when im using export anyone knows how to fix this issue ? how can i get the color defined in :root? thanks!

Zephyr answered 27/4, 2020 at 13:55 Comment(4)
Does this answer your question? Accessing css variable in JS fileReider
im not sure how to use getPropertyValue, because i need to pass an element. which element do i pass ?Zephyr
You can use document.documentElementReider
@GalShtengel define :root variables on the top of the file and styles.Pulmotor
E
0

I found a solution in this website. Here's the gist, in case the post gets deleted.

Create a modular scss file containing your scss variables, or import them from the original files using @use.

// _globalVars.scss

$mobile-breakpoint: 900px;
// exporterFile.module.scss

@use './globalVars'

$new-variable: red;

:export {
  mobileBreakpoint: globals.$mobile-breakpoint;
  newVariable: $new-variable;
}

As you can see above, the required variables were exported using the :export{} syntax. These can then be imported into a JS or TS file.

import myScssVars from 'exporterFile.module.scss'

console.log(myScssVars); // { mobileBreakpoint: '900px', newVariable: 'red' }

Unfortunately these are imported as a readonly key value string pair. VSCode type annotation screenshot.

If anyone finds out how to get inferred types in this, consider answering my question on this!

Epicardium answered 1/11, 2022 at 12:15 Comment(0)
Z
-1

Edit: found this library react-css-vars and refactor this code to use it with React

Zephyr answered 28/4, 2020 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.