{{announcement.body}}
{{announcement.title}}

Use Sass for CSS in Your React Apps

DZone 's Guide to

Use Sass for CSS in Your React Apps

Here's a tutorial that will teach you how to use Sass for your CSS when building React JavaScript applications, including configuring SCSS files.

· Web Dev Zone ·
Free Resource

Writing JavaScript code is only part of the puzzle when you develop web applications with React. You also need to implement the design with CSS style sheets. As your apps get larger, however, this becomes harder and harder to manage.

That’s where Sass comes in. Sass allows you to extend the CSS language with variables, divide style sheets into multiple files, and more. Sass also compiles its source files into a single CSS file that you can include in your web page just like any other CSS style sheet.

Looking to get started with Sass and SCSS? Check out our Introduction to SCSS.

In this blog post, you’ll learn how to integrate Zurb’s Foundation framework using Sass mixins to minimize your CSS size and make more semantic markups.

Sass

Create Your React Application with Sass

You will be using the Create React App command-line tool to create the application. First of all, make sure that you have installed Node on your system with a version greater than 10. If you are unsure which Node version you have, open a terminal and run the following command.

Shell
 




xxxxxxxxxx
1


 
1
node -v



Provided your Node version is up to date, the Create React App command-line tool can be run without any installation. In the terminal, navigate to a directory of your choice and run the following command.

Shell
 




xxxxxxxxxx
1


 
1
npx create-react-app react-calculator



This will create a new folder, react-calculator initialize the React application and download all necessary packages. After a minute or two, once the process has finished, change into the new folder with the command below.

Shell
 




x


1
cd react-calculator



Set Up Authentication for Your React App

Any serious web application will need some sort of user authentication. Implementing your own not only takes time and effort but can also introduce security risks if you don’t know exactly what you are doing. Okta lets you set up authentication with just a few commands.

If you don’t already have an account with Okta, you need to register for a free account. Open your browser and navigate to https://developer.okta.com. Click on Create Free Account and complete the registration process.

Once you are done you can see your Okta developer dashboard. Click on Applications > Add Application to register a new application. On the next screen, choose Single Page App and click Next.

Okta developer dashboard

The following screen lets you edit the application’s settings. Under Allowed grant types, check the box Authorization Code. Then make sure that the port number is 3000. Change the base URI to http://localhost:3000/ and set the Login Redirect URI to http://localhost:3000/implicit/callback.

Once you are done, you will see a Client ID which you will need in a minute.

React calculator setup

Set Up Authentication in Your React Sass App

Okta has created a tool to add authentication to React applications in seconds. It uses the Angular Schematics command-line tool to inject code into your skeleton application. Install the Schematics CLI on your system by running the following command in your terminal.

Shell
 




xxxxxxxxxx
1


1
npm i -g @angular-devkit/schematics-cli@0.803.20



TIP: Depending on your system, you might need to run this command using sudo.

You might be asking why I am telling you to use an Angular tool when you are developing a React application? It turns out that this tool is generic and works for Angular and Vue too! Not only that, but it even has support for Ionic and React Native!

Install OktaDev Schematics:

Shell
 




xxxxxxxxxx
1


1
npm i -E @oktadev/schematics@1.1.1



Now, add Okta for authentication to your React application by running the command below.

Shell
 




xxxxxxxxxx
1


1
schematics @oktadev/schematics:add-auth



You will be asked for your issuer’s URL. This can be found at API > Authorization Servers in your Okta dashboard. .

You will also need the application’s client ID which you received when earlier when setting up your application. Once the questions have been answered, the schematic will insert all the necessary code into your application to provide the authentication flow. Pretty neat, don’t you think?

Implement a React Calculator with Sass

Now it’s time to implement the calculator. This calculator is a nice demonstration of how to use stack operations to process user input and perform mathematical operations. The calculator has four basic operations +, -, *, and /, as well as a % button. It takes care of operator precedence.

Create a new file called src/Calculator.js and paste the following code into it.

JavaScript
 




xxxxxxxxxx
1
153


 
1
import React from 'react';
2
 
          
3
class Calculator extends React.Component {
4
  constructor(props) {
5
    super(props);
6
    this.state = {
7
      stack: ['='],
8
      display: '0'
9
    }
10
  }
11
 
          
12
  numberPressed(val) {
13
    const s = this.state;
14
    if (typeof s.stack[s.stack.length - 1] !== 'number') {
15
      s.display = val;
16
      s.stack.push(parseInt(s.display, 10));
17
    } else {
18
      s.display += val;
19
      s.stack[s.stack.length - 1] = parseInt(s.display, 10);
20
    }
21
    this.setState(s);
22
  }
23
 
          
24
  operatorPressed(val) {
25
    const s = this.state;
26
    const precedenceMap = {'+': 0, '-': 0, '*': 1, '/': 1};
27
    this.ensureNumber(s);
28
    const precedence = precedenceMap[val];
29
    let reduce = true;
30
    while (reduce) {
31
      let i = s.stack.length - 1;
32
      let lastPrecedence = 100;
33
 
          
34
      while (i >= 0) {
35
        if (typeof s.stack[i] === 'string') {
36
          lastPrecedence = precedenceMap[s.stack[i]];
37
          break;
38
        }
39
        i--;
40
      }
41
      if (precedence <= lastPrecedence) {
42
        reduce = this.reduceLast(s);
43
      } else {
44
        reduce = false;
45
      }
46
    }
47
 
          
48
    s.stack.push(val);
49
    this.setState(s);
50
  }
51
 
          
52
  equalPressed() {
53
    const s = this.state;
54
    this.ensureNumber(s);
55
    while (this.reduceLast(s)) {}
56
    s.stack.pop();
57
    this.setState(s);
58
  }
59
 
          
60
  percentPressed() {
61
    const s = this.state;
62
    this.ensureNumber(s);
63
    while (this.reduceLast(s)) {}
64
    const result = s.stack.pop() / 100;
65
    s.display = result.toString(10);
66
    this.setState(s);
67
  }
68
 
          
69
  acPressed() {
70
    const s = this.state;
71
    s.stack = ['='];
72
    s.display = '0';
73
    this.setState(s);
74
  }
75
 
          
76
  cePressed() {
77
    const s = this.state;
78
    if (typeof s.stack[s.stack.length - 1] === 'number') { s.stack.pop(); }
79
    s.display = '0';
80
    this.setState(s);
81
  }
82
 
          
83
  ensureNumber(s) {
84
    if (typeof s.stack[s.stack.length - 1] === 'string') {
85
      s.stack.push(parseInt(s.display, 10));
86
    }
87
  }
88
 
          
89
  reduceLast(s) {
90
    if (s.stack.length < 4) { return false; }
91
    const num2 = s.stack.pop();
92
    const op = s.stack.pop();
93
    const num1 = s.stack.pop();
94
    let result = num1;
95
    switch (op) {
96
      case '+': result = num1 + num2;
97
        break;
98
      case '-': result = num1 - num2;
99
        break;
100
      case '*': result = num1 * num2;
101
        break;
102
      case '/': result = num1 / num2;
103
        break;
104
      default:
105
    }
106
    s.stack.push(result);
107
    s.display = result.toString(10);
108
    return true;
109
  }
110
 
          
111
  render() {
112
    return (
113
      <div className="calculator-container">
114
        <div className="calculator">
115
          <p className="display">{this.state.display}</p>
116
          <div className="calculator-buttons">
117
            <button className="reset-button" onClick={this.acPressed.bind(this)}>AC</button>
118
            <button className="reset-button" onClick={this.cePressed.bind(this)}>CE</button>
119
            <button className="operator-button" onClick={this.percentPressed.bind(this)}>%</button>
120
            <button className="operator-button" onClick={this.operatorPressed.bind(this, '/')}>÷</button>
121
            <button className="number-button" onClick={this.numberPressed.bind(this, '7')}>7</button>
122
            <button className="number-button" onClick={this.numberPressed.bind(this, '8')}>8</button>
123
            <button className="number-button" onClick={this.numberPressed.bind(this, '9')}>9</button>
124
            <button className="operator-button" onClick={this.operatorPressed.bind(this, '*')}>x</button>
125
            <button className="number-button" onClick={this.numberPressed.bind(this, '4')}>4</button>
126
            <button className="number-button" onClick={this.numberPressed.bind(this, '5')}>5</button>
127
            <button className="number-button" onClick={this.numberPressed.bind(this, '6')}>6</button>
128
            <button className="operator-button" onClick={this.operatorPressed.bind(this, '-')}>-</button>
129
            <button className="number-button" onClick={this.numberPressed.bind(this, '1')}>1</button>
130
            <button className="number-button" onClick={this.numberPressed.bind(this, '2')}>2</button>
131
            <button className="number-button" onClick={this.numberPressed.bind(this, '3')}>3</button>
132
            <button className="operator-button" onClick={this.operatorPressed.bind(this, '+')}>+</button>
133
            <button className="number-button" onClick={this.numberPressed.bind(this, '0')}>0</button>
134
            <button className="number-button" onClick={this.numberPressed.bind(this, '.')}>.</button>
135
            <button className="equal-button" onClick={this.equalPressed.bind(this)}>=</button>
136
          </div>
137
        </div>
138
        <div className="calculator-stack">
139
          <h4>Stack</h4>
140
          <table>
141
            <tbody>
142
              {this.state.stack.map(el => (<tr><td>{el}</td></tr>))}
143
            </tbody>
144
          </table>
145
        </div>
146
      </div>
147
    );
148
  }
149
}
150
 
          
151
export default Calculator;
152
 
          
153
 
          


You can see that the HTML of the calculator consists of groups of buttons. Each button is linked to a callback function in the Calculator class. To give you an insight into what the stack contains at any time, a separate div contains a table displaying the stack entries.

Now open src/Home.js and remove the import of logo.svg. Add the following import to the top of the file.

JavaScript
 




xxxxxxxxxx
1


1
import Calculator from './Calculator';



Further down in the file, replace the render() function with the following.

JavaScript
 







Cool! The calculator should be functional. If you run npm start, you should be able to open your browser at http://localhost:3000 and see a Login button. After logging in you will be able to use the calculator. But we haven’t styled it yet, so it won’t look nice.

Style Your Calculator in React With Sass

Back in the days when CSS was all the rage, it came with a promise of a bright future where content and style were completely separated. Your HTML code would only contain the actual content and the markup would be completely semantic. One of the promises was that class names would only relate to the meaning of the content and not the way that it was displayed on the screen.

Then along came CSS frameworks. They introduced CSS classes for creating a responsive grid layout, such as col-md-4. Other classes determined the size of buttons, such as btn-sm. While incredibly useful, this broke the separation of content and design.

Using Sass together with the Foundation CSS framework, it is possible to regain this strict separation. You might have noticed in the code above, that I have used semantic className attributes. The classes tell you what is contained in a div and not how it should be shown on the screen. This actually has an accessibility advantage because screen readers can group the contents in a meaningful way.

To get started with Sass and Foundation, install two more packages. In the terminal run the following command.

Shell
 




xxxxxxxxxx
1


1
npm i -E sass@1.23.7 foundation-sites@6.6.1



There are actually two Sass packages available through npm. node-sass is generally faster but does require a compilation step during installation. I have opted for the more compatible sass package which is a pure JavaScript implementation of the Sass language.

Copy the default settings from the Foundation folder to your src/ folder by running the following command in a terminal.

Shell
 




xxxxxxxxxx
1


1
cp node_modules/foundation-sites/scss/settings/_settings.scss src/



Now open src/_settings.scss and, and change line 63 (@import 'util/util';) to the following:

SCSS
 




xxxxxxxxxx
1


1
@import '~foundation-sites/scss/util/util';



If you look through the settings file, you can see that it defines a huge number of Sass variables. Foundation is highly customizable but the default settings provide a good starting point. Now rename src/App.css to src/App.scss and replace its content with the following.

SCSS
 




xxxxxxxxxx
1
68


 
1
@import 'settings';
2
@import '~foundation-sites/scss/foundation';
3
 
          
4
.App {
5
  text-align: center;
6
  @include xy-grid-container;
7
}
8
 
          
9
.login-buttons {
10
  display: flex;
11
  justify-content: flex-end;
12
 
          
13
  button {
14
    @include button;
15
  }
16
}
17
 
          
18
.calculator-container {
19
  @include xy-grid;
20
}
21
 
          
22
.calculator {
23
  @include xy-cell(12);
24
  @include breakpoint(medium) {
25
    @include xy-cell(6);
26
    @include xy-cell-offset(2);
27
  }
28
 
          
29
  .display {
30
    background-color: $light-gray;
31
    font-size: 48px;
32
    padding: 8px;
33
    overflow: hidden;
34
  }
35
 
          
36
  .calculator-buttons {
37
    @include xy-grid-layout(4, 'button');
38
  }
39
 
          
40
  button {
41
    @include button;
42
 
          
43
    &.reset-button {
44
      @include button-style($warning-color, auto, auto);
45
    }
46
 
          
47
    &.number-button {
48
      @include button-style($secondary-color, auto, auto);
49
    }
50
 
          
51
    &.equal-button {
52
      width: calc(50% - 1.25rem);
53
    }
54
  }
55
}
56
 
          
57
.calculator-stack {
58
  @include xy-cell(12);
59
  @include breakpoint(medium) {
60
    @include xy-cell(2);
61
    @include xy-cell-offset(1);
62
  }
63
}
64
 
          
65
table {
66
  @include table;
67
}
68
 
          



In this style sheet, I have used a number of Sass features. I have used a number of @include statements to include mixins from the Foundation framework.

For example @include xy-cell(6); will add styles to the surrounding class to turn it into a 6 column wide cell. Note also, how I have used the $warning-color and $secondary-color variables to define the button style of the reset and the number buttons.

These variables are defined in the src/_settings.scss file. If you want to learn more about the Sass language, the official documentation is a good starting point.

How I Theme My React App With Sass is a good tutorial that teaches you more about the power of mixins.

To include the stylesheet in your application, open Home.js and change the import of App.css to the following.

JavaScript
 




xxxxxxxxxx
1


1
import './App.scss';



The React scripts installed by the create-react-app command use webpack to compile and package everything. By default, they also install the module loaders for .scss files. By changing the import above, everything should now work out of the box without any further configuration. Simply run the following command and your perfectly styled calculator will be available on http://localhost:3000.

Shell
 




xxxxxxxxxx
1


1
npm start



Congratulations, you should now see something like this in your browser.

React calculator

Learn More About React and Sass

In this tutorial, you learned how to use Sass in a React application. Using the create-react-app command makes it extremely easy to include Sass without any further configuration needed. I also showed you how to achieve truly semantic markup in your application while still using a powerful CSS framework. In this tutorial, I used Zurb’s Foundation as an example. You can achieve a similar effect when using the Bootstrap framework.

You can find the source code for this tutorial on GitHub in the oktadeveloper/okta-react-sass-example repository.

If you want to learn more about Sass, React, or the use of Schematics, feel free to check out the links below.

Please leave a comment below if you have any questions. If you liked this tutorial, follow @oktadev on Twitter to be notified when we publish new ones. We also have a YouTube channel you might like.

Further Reading

CSS Position: Relative vs Position Absolute

How to Use Sass in ASP.NET Core 2.0 MVC

Topics:
react ,css ,authentication ,authorization code

Published at DZone with permission of Holger Schmitz , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}