However, unlike vanilla CSS, you need a little bit of setup to use Sass. Find out how this works by setting up a simple React.js project and integrating Sass with it.
How to Use Sass in Your React.js Project
Like other CSS processors, Sass is not natively supported by React. To use Sass in React, you need to install a third-party dependency via a package manager like yarn or npm.
You can check if npm or yarn is installed on your local machine by running npm –version or yarn –version. If you don’t see a version number in your terminal, install npm or yarn first.
Create a React.js Project
To follow this guide, you can set up a simple React.js app using create-react-app.
First, use a command line to navigate to the folder you want to create your React project in. Then run npx create-react-app
Once you’ve set up a basic React project, it’s time to integrate Sass.
Install Sass
You can install Sass via npm or yarn. Install it via yarn by running yarn add sass or, if you prefer npm, run npm install sass. Your package manager will add the latest version of Sass to the list of dependencies in the project’s package.json file.
Rename .css Files to .scss or .sass
In the project’s folder, rename App.css and index.css to App.scss and index.scss, respectively.
After you’ve renamed those files, you need to update the imports in your App.js and index.js files to match the new file extensions as follows:
From this point forward, you should use the .scss extension for any style file you create.
Importing and Using Variables and Mixins
One of the most significant advantages of Sass is that it helps you write clean, reusable styles using variables and mixins. While it may not be apparent how you can do the same in React, it’s not so different from using Sass in projects written with plain JavaScript and HTML.
First, create a new Styles folder in your src folder. In the Styles folder, create two files: _variables.scss and _mixins.scss. Add the following rules to _variables.scss:
And add the following to _mixins.scss:
Then import variables and mixins in App.scss as follows:
Use your variables and mixins in App.scss file:
That’s how you use variables and mixins in React. Besides mixins and variables, you can also use all the other awesome features in Sass, like functions. There’s no limitation.
Using Sass in React.js
Sass provides more functionality on top of CSS, which is exactly what you’ll need to write reusable CSS code.
You can start using Sass in React by installing the sass package via npm or yarn, updating your CSS files to .scss or .sass, then updating your imports to use the new file extension. After that, you can start writing SCSS in React.