Onjsdev

Share


How To Integrate SASS to React


By onjsdev

Apr 1st, 2024

SASS is powerful tool to give style components of our pages. Let's see how to use it our React Applications.

To integrate Sass into your React project, you'll need to follow a few steps:

Set up a React project

Assuming you have Nodejs and npm installed on your machine, you can create a new React project using the following command:

npx create-react-app my-app

This command sets up a new React project called "my-app" in a directory of the same name. Once the project is created, navigate into the project folder:

cd my-app

Install node-sass

To use Sass in your React project, you need to install a package called node-sass. Run the following command to install it as a dev dependency:

npm install -D node-sass

Create a Sass file

In your React project, create a new file with a .scss extension to write your Sass code. For example, you can create a file named styles.scss in the src directory.

Write Sass code

Open styles.scss and start writing your Sass code. You can use Sass features like variables, nesting, mixins and more to organize CSS classes. Here's an example of how you can define a variable and use it in your styles:

$primary-color: #FF0000;

.container {
  background-color: $primary-color;
  padding: 20px;

  h1 {
    color: white;
    font-size: 24px;
  }
}

Import Sass file

To use the Sass styles in your React components, you need to import the Sass file you just created. Open src/App.js and add the following import statement at the top of the file:

import './styles.scss'; // path/to/scss/

Now, the styles defined in styles.scss will be applied to your React components.

6. Run the project

To see the Sass styles in action, start the development server by running the following command in your project directory:

npm start

React will compile your Sass code into CSS and apply it to your components. You can now navigate to http://localhost:3000 in your browser to view the React application with Sass styles.

Conclusion

Sass and React can be used together for creating user interfaces. As SASS provides extra features to CSS, this process will speed up. In this tutorial, we have shown how to integrate sass to a react application using the node-sass node package.

Thank you for reading.