Creating SASS Variables
In this tutorial, we’ll integrate SASS into our React project and explore the power of SASS variables. SASS extends CSS by adding programming-like features such as variables, making styles more modular and reusable. This lesson covers configuring Webpack for SASS, creating variables, and understanding their application in dynamic styling.
1. Installing Required Packages
To work with SASS, you need two additional packages:
- SASS Loader: Allows Webpack to process SASS files.
- Node SASS: Provides access to the SASS library.
Run the following command in your terminal:
npm install --save-dev sass-loader node-sass
2. Configuring Webpack for SASS
-
Update the Webpack Configuration:
In yourwebpack.config.js
file, add support for SASS files. Modify the module rules to include:module: { rules: [ { test: /\.(scss|sass)$/, // Matches both .scss and .sass files use: [ 'style-loader', // Injects styles into DOM 'css-loader', // Turns CSS into CommonJS 'sass-loader' // Compiles SASS to CSS ] } ] }
-
Save Changes:
Ensure you save the Webpack configuration file to apply these changes.
3. Renaming and Updating CSS Files
-
Rename the Existing CSS File:
Change yourapp-source.css
file extension to.scss
:app-source.scss
-
Modify Imports in Your React App:
Update the import path in yourApp.js
or main component:import './app-source.scss';
-
Start the Server:
Restart the server to apply changes:npm start
4. Creating and Using SASS Variables
-
Define Variables:
In your.scss
file, define variables using the$
syntax:$background-color: #f0f0f0; $text-color: #333; .custom { background-color: $background-color; color: $text-color; }
-
Use Variables in Styles:
Replace hardcoded values in your styles with variables. For example:.button { background-color: $background-color; color: $text-color; }
5. Testing SASS Variables
- Save the
.scss
file and refresh your application. - Inspect the changes in your browser to ensure the styles are applied correctly.
6. Exploring Dynamic Variables
SASS variables can simplify updates to styles across your application. For instance:
-
Global Text Colors:
$primary-color: #3498db; $secondary-color: #2ecc71; h1 { color: $primary-color; } p { color: $secondary-color; }
-
Dynamic Backgrounds:
$bg-dark: #34495e; $bg-light: #ecf0f1; body { background-color: $bg-light; } .footer { background-color: $bg-dark; }
Conclusion
You’ve successfully integrated SASS into your React project and learned to use SASS variables for cleaner and more maintainable styles. In the next lesson, we’ll delve deeper into SASS features, such as importing external files for modular styles.
Ready to Level Up Your Skills?
Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!
Enroll Now for Free!