Getting started with Sass in React — part 1

Sass is a Syntactically Awesome Style Sheets, which means is that it is just an improved and feature-rich version of CSS, and at the end, it compiles down to CSS. This tool makes your work much easier, you write less, you make your code reusable and more readable.

Setup in React

npm i node-sass

Now we can directly import our sass files into our components as we did with CSS. Our file extension should be scss like this style.scss .

Don’t worry if VS Code cannot auto-suggest you scss files, as it should be normal behavior if it is no issue with my VS Code :)

import React from 'react';
import './style.scss';
const SomeComp = () => {
return (
<div className="outer">
<div className="inner">Hello world</div>
</div>
);
};
export default SomeComp;

Now we are done with our setup let’s dive into sass itself.

For the most part, it has no difference with CSS and any CSS code works inside sass. Let’s apply some style to our ‘outer’ class.

.outer{
background-color: teal;
width: 500px;
height: 500px;
display: flex;
align-items: center;
justify-content: center;
}

Nesting, or parent-child relation

.outer .inner {
/* Some styles */
}

But with Scss it is much easier and more readable. You can just write selectors inside selectors replicating their parent-child behavior in HTML elements, like this:

.outer{
background-color: teal;
width: 500px;
height: 500px;
display: flex;
align-items: center;
justify-content: center;
.inner{
font-size: 46px;
color: white;
font-family: sans-serif;
}
}

Now our ‘inner’ class is isolated and these styles will be only applied if it is a child of element with ‘outer’ class name.

Pseudo-class and pseudo-element

//...
.inner{
font-size: 46px;
color: white;
font-family: sans-serif;
transition: .3s ease-in-out margin-bottom;
&:hover{
margin-bottom: 10px;
}
&::before{
content: "\2713";
}
}
//...

See easy-peasy :) Here is a link to all our code in codesandbox.io. https://codesandbox.io/s/pensive-chatterjee-7oqt2?file=/src/some-comp/some-comp.scss:310-350

These features are the tip of iceberg in Sass world. But it should serve you as a foundation to get started using Sass. To keep my content enjoyable and easy to digest I would finish our first part here and in the second part we discover features like extracting block of code and make them reusable, importing Scss files within each other, working with variables, and much more. I shall include a link to the second part as soon as I finish writing. Happy coding :)

React dev.