Getting started with Sass in React.js — part 2

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;
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;
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.

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



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store