Include Sass to React Application

You can style your application using plain CSS but Sass has much better features like variables, mixins, nesting and much more which makes is easy to write CSS.

Let’s start with installing it to your react project. In your command line, go to your project directory and execute the below mentioned command.

npm install node-sass --save
// or using yarn
yarn add node-sass

Restart your application using “npm start” and you will see Sass file is loading.

Now, you should try to change the file extension from .css to .scss so that we are using Sass as application standard. In your application now, you can import the .scss file like below mentioned.

import './App.scss';

If you like to use with CSS module, react developers have made it easy to do so. All you have to is follow the convention like: filename.module.scss If using CSS module, class names and animations are scoped locally by default. The benefit of using CSS module is that the same class name does not clash with same class name used in another component.

//Input.module.scss
.elementStyle { font-size: 18px; }
//Button.module.scss
.elementStyle { font-size: 22px; }

In the above example you can see that same class names are used in two different stylesheets but when reacts runs this, it will name those classes following convention like : [filename]\_[classname]\_\_[hash]

Include the CSS module Sass file into your JavaScript file. You can import the whole css file and can add it into the class like InputStyle.elementStyle using curly brackets.

import React from 'react';
import InputStyle from './Input.module.scss';

const InputElement = props => {
    return (<input type={props.type} className={InputStyle.elementStyle}  
            placeholder={props.placeholder} name={props.placeholder} 
           onChange={props.changed} />)
};

export default InputElement;

You can also include just one class name from your module stylesheet. In the example, you can see we just imported one class name called elementStyle to destructure the file in curly brackets and can use the class name.

import React from 'react';
import {elementStyle} from './Input.module.scss';

const InputElement = props => {
    return (<input type={props.type} className={elementStyle}  
            placeholder={props.placeholder} name={props.placeholder} 
           onChange={props.changed} />)
};

export default InputElement;

I hope this post was helpful to you. If you like my post, follow me @twitter/andramazo.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top