react js-tutorial

Styling React Using Sass

What is Sass?

The CSS pre-processor known as Sass, which stands for Syntactically Awesome Style Sheets, enables us to use variables, inline imports, nested rules, mixins, functions, and many other features. It assists us in maintaining a well-organized stylesheet.

Why Sass?

We can use variables in our stylesheet

$main-color: #444
h2 {
color:$main-color
}
header{
background-color:$main-color
}

We can use the mixin

@mixin default-type {  
  padding: 20px;  
  font-size: 16px;  
  font-weight:bold;
}
p {
 @include default-type;
}
article{
 @include default-type;
}

The best part nested rules

header{
  background-color: #000;
    p{
      font-size:12px;
      font-weight: bold;
     }
}

It helps us to keep our stylesheet well organized.

How to use in React js?

1.Create your React js project.

yarn create react-app sass-react-medium

2.Now install the node-sass module to your react project.

yarn add node-sass

3.In your project src directory create an app.scss file.

4.Now add the below code in your app.js file

import React from 'react';
import './App.scss';

function App() {
  return (
    <>
      {/* Variable Example */}
      <h1>This is a variable example</h1>
     
     {/* Nested Rules */}
     <div id="nested">
        <h3>This is a nested rules example</h3>
     </div>

     {/* Interpolation Example */}
       <p className="interpolation">Interpolation Example.</p>

       {/* Function Example */}
       <div id="function">
       <h3>This is a function example</h3>
       </div>

       {/* Mixin Example */}
      <div id="mixin">
      <p>This is mixin Example</p>
      </div>
    </>
  );
}

export default App;

5. Open your app.scss file and add below sass code there.

//Variable Example
$main-color : red;

h1{
    color:$main-color;
    font-size: 20px;
}

// Nested Rules
$bgcolor : #c1c1c1;

#nested {
    background-color: $bgcolor;
    h3{
        color: green;

    }
}

 //Interpolation Example
@mixin text-style($name, $bold-or-normal, $size, $color) {
    #{$name} {
      font-size: #{$size}px;
      font-weight: #{$bold-or-normal};
      color: #{$color};
    }
  }

@include text-style(".interpolation", bold, 25, blue);

//Function Example

@function invert($color, $amount: 100%) {
    $inverse: change-color($color, $hue: hue($color) + 180);
    @return mix($inverse, $color, $amount);
  }
  
  $primary-color:green;
  #function {
    background-color: invert($primary-color, 80%);
    h3{
        color: white;
    }
  }

  //Mixin Example

  @mixin default-text-style {  
    padding: 20px;  
    font-size: 16px;  
    font-weight:bold;
  }
  
  #mixin{
      p{
          @include default-text-style
      }
  }

In the above code, I have given the example of all the main features of sass like how to use variable, mixin, function and interpolation. There are more things we can do with SASS.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.