How to dynamically update SCSS variables using ReactJS?
We can dynamically update SCSS variables using ReactJS with the help of a project by achieving theme switching of the card component between light and dark theme.
- Basic knowledge of npm & create-react-app command.
- Basic knowledge of HTML/CSS.
- Basic Knowledge of react components & ES6.
Basic Setup: You will start a new project using create-react-app so open your terminal and type:
npx create-react-app react-scss
Now go to your react-scss folder by typing the given command in the terminal:
Required module: Install the dependencies required in this project by typing the given command in the terminal.
$ npm install node-sass
For developers using yarn:
$ yarn add node-sass
Project Structure: The file structure in the project will look like this.
- We are going to create a card component using JSX and style it using SCSS.
- After structuring and styling the card component, we are going to make use of react useState hook to manage the state of the ‘darkTheme’ as per the user.
- There will be a button with onClick event listener which will set the state of ‘darkTheme’ as false if it previously was true and vice versa.
- We are going to use useEffect react hook that will fire up every time there is a change in the state of ‘darkTheme’.
- useEffect will cause a side effect and change the value of SCSS variables : $background-color and $text-color.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: