Getting started with Sass in React.js — part 2

Ali Toshmatov
2 min readMar 23, 2021

You can check out the first part here.

Extracting reusable code

Like you do in most programming languages you can extract fragments of your code to make it reusable. In Sass, it is pretty simple let's say we are going to center any child elements using flex, we can write:

@mixin center{
display: flex;
align-items: center;
justify-content: center;
}

Notice that every keyword in Sass starts with the ‘@’ symbol. Here we used the mixin keyword which tells our Sass compiler that this is a block of code that could be reused somewhere. Now to use this block we can just call it anywhere using the ‘include’ keyword and name of our mixin:

.outer{
background-color: teal;
width: 500px;
height: 500px;
@include center;
}

Variables in Sass

As we can use variables in CSS we can also use them in Sass. The declaration of a variable is pretty easy, we just need to put the ‘$’ sign before the variable name and we are good to go:

$mainWidth: 500px;
$primaryBgColor: teal;

Using them is also pretty simple:

.outer{
background-color: $primaryBgColor;
width: $mainWidth;
//...

Splitting code into separate files and Importing in Sass

When you are working on large-scale projects you probably use a ton of Sass and managing them could be quite painful. To ease our work we should start separating our code into smaller files, we can start it by separating variables and mixins into other files. And hopefully, we don’t have to import every file into our js component files, what we can do instead is use built-in import from Sass. First of all, let's separate our variables and mixins.

Now we can import our mixins and variables into our scss file:

@import "./mixins.scss";
@import "./variables.scss";

Just like that. You can check out the complete sandbox project here

Keep in mind that, although we are extracting our code into mixins or setting some variables, in the end, after building your react app this all code gets compiled into CSS code, and since CSS doesn’t have any concept to make something like mixins it just inserts every mixin fragments into our CSS file and also variable won’t be turned into CSS variables instead it gets their direct value.

I will be so happy if this article gave you any value.

--

--