React Sass
Sass (Syntactically Awesome Stylesheets) is a CSS preprocessor.
Sass allows you to use features not yet available in CSS, such as variables, nested rules, mixins, functions, and more.
Sass files are executed on the server, and the generated CSS is sent to the browser.
You can learn more about Sass in our Sass Tutorial tutorial.
Installing Sass
Run the following command in your terminal to install Sass:
npm i sass
Now you are ready to include Sass files in your project!
Create a Sass File
Creating a Sass file is the same as creating a CSS file, but Sass files use the .scss extension.
In a Sass file, you can use variables and other Sass features.
Example
Create a variable to define the text color:
my-sass.scss file code:
my-sass.scss
$myColor
:
red
;
h1
{
color
:
$myColor
;
}
Import a Sass file just like importing a CSS file:
Example
import
React from
'react'
;
import
ReactDOM from
'react-dom/client'
;
import
'./my-sass.scss'
;
const
Header
=
(
)
=>
{
return
(
<>
<
h1
Hello Style
!
h1
<
p
Add a little style
!
.
p
)
;
}
const
root
=
ReactDOM.
createRoot
(
document.
getElementById
(
'root'
)
)
;
root.
render
(
<
Header
/>
);
In the above code, we created a Sass file my-sass.scssand used the Sass variable inside it $myColor to define h1 for the color. Then, in the index.js we imported this Sass file just like a normal CSS file, and in the Header component we used these styles.