
Sass Styling in ReactJS
✅ SASS Styling in ReactJS
SASS (Syntactically Awesome Stylesheets) is a CSS preprocessor that adds powerful features like variables, nested rules, mixins, and functions to standard CSS.
In ReactJS, you can easily integrate and use SASS for styling your components.
📌 1. Install SASS in ReactJS
To get started, install SASS using npm or yarn:
npm install sass// Mixin for responsive design@mixin respond($breakpoint) { @if $breakpoint == mobile { @media (max-width: 600px) { @content; } }}
App.scss
@import './variables';@import './mixins';h1 { color: $primary-color; @include respond(mobile) { font-size: 24px; }}
🛠 Explanation:
@import
→ Import SASS files for better maintainability.@mixin
→ Reusable styles for responsive design using media queries.
📌 6. Conditional Styling with SASS
You can use if-else statements to apply conditional styles.
Example:
$theme: light;.container { background-color: if($theme == light, #fff, #333); color: if($theme == light, #000, #fff);}
🛠 Explanation:
if(condition, trueValue, falseValue)
→ Applies styles conditionally.
📌 7. Nesting and Parent Selector (&
)
The &
symbol refers to the parent selector, making nesting simple.
Example:
.card { padding: 20px; border: 1px solid #ccc; &__title { font-size: 24px; color: #333; } &__description { font-size: 16px; color: #777; }}
🛠 Explanation:
&__title
and&__description
follow BEM (Block Element Modifier) naming.
📌 8. Using SASS Variables in JSX
You can dynamically apply variables using inline styles.
import React from 'react';import './App.scss';const App = () => { const primaryColor = '#007bff'; return ( <div> <h1 style={{ color: primaryColor }}>Hello, React with SASS!</h1> </div> );};export default App;
✅ Final Thoughts
Use SASS for scalable and maintainable styles.
Prefer SASS Modules for component-specific styles.
Use variables and mixins for consistent design.
Apply conditional styling using
if()
statements.