Sass/SCSS in React
Modern React applications often require advanced styling techniques like variables, nesting, mixins, and modular styles. Sass/SCSS is a powerful CSS preprocessor that extends CSS with these capabilities, making styles more maintainable, reusable, and readable.
What is Sass/SCSS?
- Sass (Syntactically Awesome Stylesheets) is a CSS preprocessor.
- SCSS is a syntax of Sass that is fully CSS-compatible.
- Sass allows you to use features not available in plain CSS, such as:
- Variables
- Nesting
- Mixins
- Functions
- Partials and imports
- Inheritance
Installing Sass in a React Project
If you’re using Create React App or Vite, you can install Sass easily:
- React automatically compiles
.scssfiles into CSS.
npm install sass
# or
yarn add sass
Using Sass/SCSS in React
1. Creating an SCSS File
Create a file App.scss:
$primary-color: #007bff;
$secondary-color: #6c757d;
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
.button {
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
&--primary {
background-color: $primary-color;
color: white;
&:hover {
background-color: darken($primary-color, 10%);
}
}
&--secondary {
background-color: $secondary-color;
color: white;
&:hover {
background-color: darken($secondary-color, 10%);
}
}
}
2. Importing SCSS in React
import React from "react";
import "./App.scss";
export default function App() {
return (
<div>
<button className="button button--primary">Primary</button>
<button className="button button--secondary">Secondary</button>
</div>
);
}
$primary-colorand$secondary-colorare Sass variables.&--primaryand&--secondaryuse nesting for cleaner CSS.darken()is a Sass function to adjust color brightness.
3. Advanced Sass Features
Mixins
Mixins allow reusable blocks of styles:
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.container {
@include flex-center;
height: 100vh;
}
Partials & Imports
Split styles into multiple files for organization:
// _variables.scss
$primary-color: #007bff;
// _buttons.scss
@import 'variables';
.button {
background-color: $primary-color;
}
Functions
Create reusable logic for styles:
@function spacing($factor) {
@return $factor * 8px;
}
.card {
margin: spacing(2);
padding: spacing(3);
}
Nesting
Write hierarchical styles cleanly:
.nav {
ul {
list-style: none;
li {
display: inline-block;
margin-right: 20px;
}
}
}
Benefits of Using Sass/SCSS in React
- Cleaner Code: Nesting and variables reduce repetition.
- Reusable Styles: Mixins and functions make components modular.
- Scalable Projects: Easy to maintain large codebases.
- Dynamic Styling: Variables and functions allow flexible design changes.
- Community & Ecosystem: Widely supported, compatible with most tools.
