Home > Software engineering >  How to Access SASS/SCSS variables in your React Components inline style
How to Access SASS/SCSS variables in your React Components inline style

Time:09-28

Let's say I have a button style in my JSX like this

const btnStyle = {
  width: '100%',
  backgroundColor: '$green-d1',
  border: 0,
};

how can I access the $green-d1 variable from my scss?

CodePudding user response:

1. With Interoperable CSS's :export feature

:export {
  greenD1: $green-d1;
}
import styles from "./styles.scss";

const btnStyle = {
  width: '100%',
  backgroundColor: styles.greenD1,
  border: 0,
};

For this to work, you either need to use CSS module or configure css-loader correctly by setting mode to "icss".

2. With a CSS variable

:root {
  --green-d1: #{$green-d1};
}
const styles = window.getComputedStyle(document.documentElement);
const greenD1 = styles.getPropertyValue('--green-d1');

const btnStyle = {
  width: '100%',
  backgroundColor: greenD1,
  border: 0,
};
  • Related