This tutorial is out of date and no longer maintained.
With the upgraded Create React App released recently, we got a lot of new tools to play with. Sass is one that I’m excited to have built-in since we used to have .scss
files compile and write to .css
files right in our folder structure. Messy files when you have two of the same styles.scss and styles.css.
Create React App 2 makes it super easy to use Sass in 1 line.
You may be concerned about using Sass in React. Isn’t a smarter way to write styles with CSS-in-JS libraries like styled-components or aphrodite? I believe that adding Sass support to Create React App will be a big help to beginners of React. How do I use Sass in React is one of the questions I always hear from people getting into React. With the React 16.6 additions like React.memo()
and the React 16.7 functional additions like hooks, starting with React will be easier than ever!
The steps to use Sass in Create React App are:
First, install node-sass
Then, change .css
files to .scss
Finally, once we’ve changed the file name from .css
to .scss
, we can import the Sass:
Done! Create React App will know to parse your .scss
files and add the styles to your project.
How do we share variables across files? We are able to import our Sass files from other Sass files. Let’s say you create a variables file:
We can import this inside of another file like we normally would in Sass:
If we want to use any 3rd party libraries like Bulma (currently my favorite) or Bootstrap, we don’t need to import the entire CSS library anymore.
With Sass in React, we can import just the files we need. First, we have to install Bulma.
If we look at Bulma’s GitHub in the sass/
folder, we can see where they place their .sass
files. Notice they are using .sass
and we are using the .scss
variant. No problems, node-sass can read and @import
both!
Import files from node_modules
using tilde (~
).
The ~
let’s webpack and Create React App know to look in the node_modules/
folder for the files we need. Let’s add a few of the files we need to our app:
Now, we can use Bulma’s button and section.
This approach lets us keep our CSS bundle sizes as small as possible as we only import what we need.
Using Sass in React is a quick way to get styling in your app. It is also recommended to look at CSS-in-JS solutions so that we can create even more modular CSS in our component-based React apps.
Here’s the CodeSandbox with the demo of Sass in Create React App 2:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!