React Sass

Sass (Syntactically Awesome Stylesheets) is a CSS preprocessor.

Sass allows you to use features that do not yet exist in CSS, such as variables, nested rules, mixins, functions, and so on.

Sass files are executed on the server, and the generated CSS is sent to the browser.

You can learn more about Sass in ourSass Tutorialfor more information about Sass.

Install Sass

Run the following command in the terminal to install Sass:

npm i sass

Now you are ready to include Sass files in your project!

Create a Sass File

The way to create a Sass file is the same as creating a CSS file, but the extension of a Sass file is.scss。

In a Sass file, you can use variables and other Sass features.

Example

Create a variable to define the color of the text:

my-sass.scss file code:

my-sass.scss

$myColor: red;

h1 {
  color: $myColor;
}

Import the 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 filemy-sass.scssand used a Sass variable in it$myColorto defineh1the color. Then, weindex.jsimported this Sass file in the same way as a normal CSS file, and inHeaderthe component used these styles.

Other Extensions