Onjsdev

Share


How To Integrate SASS with React


By onjsdev

Jul 13th, 2024

SASS is a preprocessor that adds power to CSS. If you want to integrate SASS with a React Application, here is a step-by-step guide.

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

Then, install the node-sass package using npm or yarn. This package allows you to compile SASS/SCSS files to CSS.

npm install -D node-sass

Create a Sass file

Next, create your SASS files with a .scss or .sass extension. For example, create a file named App.scss in the src directory.

/* src/App.scss */
$primary-color: #3498db;

.App {
  text-align: center;
  background-color: $primary-color;

  .App-header {
    background-color: darken($primary-color, 10%);
    height: 150px;
    padding: 20px;
    color: white;
  }
}

Import SASS Files in React Components

To use the Sass styles in your React components, you need to import the SASS file into your components. You can modify your App.js file to import the App.scss file. This allows you apply styles to the all components.

/* src/App.js */
import React from 'react';
import './App.scss';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Welcome to React with SASS</h1>
      </header>
    </div>
  );
}

export default App;

Run the project

Start your React app to see the changes.

npm start

Your React app should now be using the styles defined in your SASS file. You can now leverage the full power of SASS in your React project, including variables, nesting, mixins, inheritance, and more.

Conclusion

SASS and React is a powerful combination to create user interfaces. By following steps above, you'll have a React application integrated with SASS, allowing for more powerful and maintainable styles.

Thank you for reading.