2

I wonder if there is a way I can share my color variables in css-modules to my js (React) components?

If not, how would you do it? Have two files with color variables?

Thanks!

1

1 Answer 1

1

CSS doesn't have the concept of variables like Sass does, so I'll assume you're referring to CSS custom properties, which a lot of people refer to as "CSS variables".

These custom properties are just that - custom style properties than are set to particular elements and that can be accessed at runtime by JS through getComputedStyle + getPropertyValue. Here's an example:

const root = document.documentElement;
const div = document.querySelector('div');
const x = document.getElementById('x');

const get = (elt, key) => getComputedStyle(elt).getPropertyValue(key);

console.log(
  get(root, '--foo'), // 'Foo!'
  get(div, '--bar'), // 'Bar!'
  get(x, '--baz'), // 'Baz!'
  get(x, '--foo'), // 'Foo!' because properties cascade down
)
:root {
  --foo: 'Foo!';
}
div {
  --bar: 'Bar!';
}
#x {
  --baz: 'Baz!';
}
<div></div>
<div id="x"></div>

As far as I know, there is no official way to export values from CSS files in a way similar to what you'd do in ESM (eg export const mainColor = '#ff0000';).

Sass however supports that, the syntax is as follow and requires a proper support from the sass processor you're using:

// colors.scss
:export {
  main-color: #ff0000;
}
import colors from './colors.scss';
console.log(colors['main-color']); // '#ff0000'
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I'm using variables in CSS-modules, like you can se here github.com/css-modules/css-modules/blob/master/docs/… And it's these variables/values I'm asking if I can use in JS/(react) somehow :) Maybe I have the wrong terminology or something? I have always called them variables :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.