Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

reactjs - How to access Sass variables using javascript inside a react component?

I just want to change the value of the Sass variables shown below from theme.scss inside a react component.

theme.scss

$backgroundColor: #fff;
$secondaryColor: #000;

React Component

useEffect(() => {
  // i want to change the Sass variable here inside this hook
  // so that when the state changes the color changes
}, [state])          
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use CSS variables to achieve themes in below steps:

Add a custom data-* attribute in body of index.html file:

<body data-theme="light"> <!-- Let's name it data-theme and start with light -->
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
</body>

And, define CSS variables, as many as you need, for all (you can have more than two themes) the data-* attribute values i.e. themes:

body[data-theme='light'] {
  --body-bg: white;
  --color: black;
}

body[data-theme='dark'] {
  --body-bg: black;
  --color: white;
}

:root {
  --primary-color: green; 
  // you can also set some CSS vars (that are common to all the themes) on :root
}

And, here is an example how to use these CSS variables for a tag (or class):

body {
  color: var(--color) !important; // Here
  background-color: var(--body-bg) !important; // And, Here
  font-family: 'Segoe UI', 'Roboto'; // Ignore it, just for example
}

// example using in a class
.some-class {
  color: var(--color);
  background-color: var(--body-bg);
}

You can now create some utility functions that would switch between the themes:

export function setLightTheme() {
  document.getElementsByTagName('body')[0].setAttribute('data-theme', 'light')
}

export function setDarkTheme() {
  document.getElementsByTagName('body')[0].setAttribute('data-theme', 'dark')
}

You can import the above functions in any component to change the theme as you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...