Using SCSS in ReactJS: A Beginner’s Guide with Example

Learn how to use SCSS in ReactJS to enhance styling with variables, nesting, and mixins. Step-by-step setup guide with a working example.

Using SCSS in ReactJS: A Beginner’s Guide with Example
Introduction
Styling is an essential part of any ReactJS application, and SCSS (Sassy CSS) makes styling more powerful and maintainable. SCSS extends CSS with features like variables, nesting, and mixins, making it easier to manage large stylesheets. This blog will guide you through integrating SCSS in a ReactJS project with a practical example.
Why Use SCSS in React?
SCSS offers several advantages over plain CSS:
Variables: Store colors, font sizes, and other values for reuse.
Nesting: Organize styles in a structured way.
Mixins: Reuse style patterns across components.
Partials & Imports: Split styles into multiple files for better maintainability.
Setting Up SCSS in ReactJS
Step 1: Create a React App
If you don’t have a React app already, create one using:
npx create-react-app my-app
cd my-app
Step 2: Install SCSS
React does not support SCSS by default. Install node-sass (or sass for newer versions):
npm install sass --save
Step 3: Create an SCSS File
Inside the src
folder, create a new SCSS file:
// src/styles/main.scss
$primary-color: #007bff;
body {
font-family: Arial, sans-serif;
background-color: #f8f9fa;
}
.button {
background-color: $primary-color;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: darken($primary-color, 10%);
}
}
Step 4: Import SCSS into React Component
Now, import the SCSS file in your React component:
// src/App.js
import React from "react";
import "./styles/main.scss";
const App = () => {
return (
<div>
<h1>Welcome to SCSS in ReactJS</h1>
<button className="button">Click Me</button>
</div>
);
};
export default App;
Step 5: Run the React App
Start the development server to see the styled button:
npm start
Best Practices When Using SCSS in React
Use Module SCSS for scoped styles:
// src/components/Button.module.scss
.button {
background-color: blue;
color: white;
}
import styles from "./Button.module.scss";
<button className={styles.button}>Click</button>;
Organize SCSS Files into separate folders (e.g.,
styles
,components
).Avoid Global Styles to prevent conflicts.
Use Variables & Mixins for better reusability.
Conclusion
SCSS significantly enhances CSS by providing features like variables, nesting, and mixins, making it a great choice for styling ReactJS applications. By following this guide, you can integrate SCSS into your React project efficiently.