[go: up one dir, main page]

DEV Community

Cover image for How to use SCSS in React?
Chetan Rohilla
Chetan Rohilla

Posted on • Edited on • Originally published at w3courses.org

How to use SCSS in React?

SCSS stands for Sassy Cascading Style Sheets or Sassy CSS. It is a superset of the CSS language. It is also used as a file extension for SASS(syntactically awesome style sheets). SCSS Code are executed on the server and sends CSS to the browser. In SCSS, we can create dynamic css using the variable, conditions, looping etc. In this tutorial we will learn how to use SCSS in react.

Install SASS in React

npm i sass
Enter fullscreen mode Exit fullscreen mode

Create a Sass file

Sass files have the file extension .scss. And Now import your .scss file in your react component.

Using the variables in SCSS

.circle {
  $size: 100px;
  width: $size;
  height: $size;
  border-radius: $size * 0.5;
}
Enter fullscreen mode Exit fullscreen mode

The above code will compile to

.circle {
width: 100px;
height: 100px;
border-radius: 50px;
}

Applying Conditions in SCSS

$width:auto;
p{
    @mixin clearfix($width) {

       @if $width == 'auto' {

        // if width is not passed, or empty do this

       } @else {
            display: inline-block;
            width: $width;
       }
    }
}
Enter fullscreen mode Exit fullscreen mode

The above code will apply css if width is auto else it will apply css of else condition.

Dynamic Class in SCSS

$columns: 5;

@for $i from 1 through $columns {
    .columns-#{$i} {
        width: (100% / $i);
    }
}
Enter fullscreen mode Exit fullscreen mode

The above code will compile to

.columns-1 {
width: 100%;
}

.columns-2 {
width: 50%;
}

.columns-3 {
width: 33.33333%;
}

.columns-4 {
width: 25%;
}

.columns-5 {
width: 20%;
}

Each loop in SCSS

The code below will loop through key value pair in $icons.

$icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f");

@each $name, $glyph in $icons {
  .icon-#{$name}:before {
    display: inline-block;
    font-family: "Icon Font";
    content: $glyph;
  }
}
Enter fullscreen mode Exit fullscreen mode

The code below will loop through the lists $icons

$icons:
  "eye" "\f112" 12px,
  "start" "\f12e" 16px,
  "stop" "\f12f" 10px;

@each $name, $glyph, $size in $icons {
  .icon-#{$name}:before {
    display: inline-block;
    font-family: "Icon Font";
    content: $glyph;
    font-size: $size;
  }
}
Enter fullscreen mode Exit fullscreen mode

More about SASS and SCSS syntax you can read here.


Please like share and give positive feedback to motivate me to write more.

For more tutorials visit my website.

Thanks:)
Happy Coding:)

Top comments (0)