Introduction
React is the most popular JavaScript framework at present. According to Wappalyzer, React holds a 34.1% market share among JavaScript frameworks. It has an easy learning path that you can follow after learning JavaScript.
Sass is a powerful extension of CSS. Using Sass, you can implement variables, functions, nesting, and other awesome features.
This is the first part of the series "Awesome Stylesheets with Sass." We have many other posts planned, such as dark/light themes, loading skeletons, and more using Sass. You can follow me on Twitter (@surajondev) to get notified of future posts earlier.
We are going to merge these two technologies by installing and using Sass variables in ReactJS.
So, let's get started.
Environment Setup
Prerequisite
We need to have NodeJS pre-installed. NodeJS is a JavaScript runtime environment that will be beneficial for running the commands to install React and Sass.
Download NodeJS from here: https://nodejs.org/en/download/
Installing React
After installing NodeJS on your machine, you are ready to install React. Run the below command to install React.
Command:
npm create-react-app react-sass
react-sass
will be the name of your project. After the installation is complete, you can delete any unnecessary files and code.
Installing Sass
Now, it's time to install the superhero of our project, Sass. Make sure you are in the react-sass
directory and run the below command.
Command:
npm install sass
After a successful installation, you will be able to see sass
under the dependencies
property in package.json
.
Using Sass Variables
Create a stylesheet file with the name style.scss
. SCSS stands for Sassy CSS and is a superset of CSS. Sass uses this file extension for its implementation.
For variable declaration, you just need to prefix the name of the variable with $
and then the name of the variable.
$primary-color: #2C372A
You can use this variable anywhere in the file with the name $primary-color
.
Together it will look like this:
$primary-color:#33D199;
.App {
font-family: sans-serif;
text-align: center;
background-color: $primary-color;
}
Use this stylesheet by importing the file into your component. You can do this with an import command.
import "./style.scss";
Demo
You can see the live working of the project in the CodeSandbox here:
{% codesandbox react-sass-variable-r6e8jo %}
Connect with Me
Conclusion
I hope this article has helped you understand Sass and its features, along with the installation guide for your React Application. Follow me on Twitter (@surajondev) for future updates earlier.
Thanks for reading the blog post.