Styling React Using Sass | Usage | Application

If you are interested to learn about the Styling CSS

What is Sass

Sass is a CSS pre-processor. Sass files are executed on the server and sends CSS to the browser.

Can I use Sass?

If you use the create-react-app in your project, you can easily install and use Sass in your React projects. Install Sass by running this command in your terminal:

>npm i sass

Create a Sass file

Create a Sass file the same way as you create CSS files, but Sass files have the file extension .scss In Sass files you can use variables and other Sass functions:

Create a variable to define the color of the text:

$myColor: red;

h1 {
  color: $myColor;
}

Import the Sass file the same way as you imported a CSS file:

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 />);

How to Use Sass and Styled Components in a React JS Application

There is a battle raging in the online development community about whether or not people should be using CSS-in-JS, or CSS-in-Javascript. This post is not to agree or disagree with any of those viewpoints, but rather to give an introduction so you can decide for yourself.

The two tools we’ll be covering today are Styled Components, which is a CSS-in-JS library that makes it easy to implement in a React js project. The other tool is called Sass, which has been a popular tool for the past few years in the javascript world.

For each example, we’ll be creating a social card component with an image, username, timestamp, user photo, and status. It should also be noted that these aren’t React specific. You could use these in Vuejs, Angular, or anything else you’re building in javascript.

Why Do People Argue Over CSS-in-JS?

CSS-in-JS

The concept of CSS-in-JS started making waves when it was discussed in 2014. Since then, many different libraries have been created to try and make this concept a reality. A few of these libraries are: Styled Components, Radium, Aphrodite, or Emotion.

I will be using Styled Components in this post, although I’d suggest checking out each of these since each has it’s own syntax and works a bit differently. The documentation for each of these is pretty good to learn the basics and see which feels most comfortable.

Installing Styled Components

Assuming we already have a React js project set up, we can add Styled Components to the project by running npm install styled-components or yarn add styled-components in the terminal. This will add the dependencies to the project and get us ready to style our application.

Creating a Card with Styled Components

The next step will be to create a component to show our card. We can use the code below to do this:

// app.js

import React from 'react';
import ReactDOM from 'react-dom';
import styled, { ThemeProvider } from 'styled-components';
import Image from './images/300.jpg';

const Card = styled.div`
  max-width: 350px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
  margin: 30px auto;
`;

const SocialCard = () => (
  <Card>
    {/* Image goes here */}
    {/* Content goes here */}
  </Card>
);

const App = () => (
  <div>
    <SocialCard />
  </div>
);

ReactDOM.render(<App />, document.getElementById('app'));

Adding Media Queries and Nesting

Inside of the Card variable, we can also drop in media queries to make things a bit more responsive. If we add a media query like the code below, you can see that when we reach a max-width of 1000px the card background turns red. This isn’t a style we actually want to add, it’s just for demonstration purposes.

import React from 'react';
import ReactDOM from 'react-dom';
import styled, { ThemeProvider } from 'styled-components';
import Image from './images/300.jpg';

const Card = styled.div`
  max-width: 350px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
  margin: 30px auto;
  @media (max-width: 1000px) {
    background-color: red;
  }
`;

const SocialCard = () => (
  <Card>
    {/* Image goes here */}
    {/* Content goes here */}
  </Card>
);

const App = () => (
  <div>
    <SocialCard />
  </div>
);

ReactDOM.render(<App />, document.getElementById('app'));

We can also nest our styles inside of the styled component, which simplifies the code we’re writing. If you have used sass or less, you are already familiar with this concept. The example below shows how we can do this to handle styles for the image in our card component:.

import React from 'react';
import ReactDOM from 'react-dom';
import styled, { ThemeProvider } from 'styled-components';
import Image from './images/300.jpg';

const Card = styled.div`
  max-width: 350px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
  margin: 30px auto;
  img {
    max-width: 100%;
  }
`;

const SocialCard = () => (
  <Card>
    <img src={Image} alt='Sample image' />
    {/* Content goes here */}
  </Card>
);

const App = () => (
  <div>
    <SocialCard />
  </div>
);

ReactDOM.render(<App />, document.getElementById('app'));

Another benefit of using CSS-in-JS is that we can mix javascript with styles. I realize this sounds kind of obvious from the concept name, but what I mean is that we can use logic to display things and we can pass variables into our styles. This can become a very powerful tool with a library like React js. We won’t keep this style since it’s a bit obnoxious, but for the purposes of illustration we can do this with string literals like so:

import React from 'react';
import ReactDOM from 'react-dom';
import styled, { ThemeProvider } from 'styled-components';
import Image from './images/300.jpg';

const border = '5px solid red';

const Card = styled.div`
  max-width: 350px;
  border: ${border};
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
  margin: 30px auto;
  img {
    max-width: 100%;
  }
`;

const SocialCard = () => (
  <Card>
    <img src={Image} alt='Sample image' />
    {/* Content goes here */}
  </Card>
);

const App = () => (
  <div>
    <SocialCard />
  </div>
);

ReactDOM.render(<App />, document.getElementById('app'));

Using a Global Theme

What if you have to update it someday? That sounds like a lot of search and replace waiting to happen. Instead we can declare the global theme variable and access it from any of our styled components. Doing so is pretty simple and is illustrated below.

import React from 'react';
import ReactDOM from 'react-dom';
import styled, { ThemeProvider } from 'styled-components';
import Image from './images/300.jpg';

const theme = {
  primary: 'red',
};

const Card = styled.div`
  max-width: 350px;
  /* border: 1px solid rgba(0, 0, 0, 0.1); */
  border: 1px solid ${props => props.theme.primary};
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
  margin: 30px auto;
  img {
    max-width: 100%;
  }
`;

const SocialCard = () => (
  <Card>
    <img src={Image} alt='Sample image' />
    {/* Content goes here */}
  </Card>
);

const App = () => (
  <ThemeProvider theme={theme}>
    <SocialCard />
  </ThemeProvider>
);

ReactDOM.render(<App />, document.getElementById('app'));

Using Sass in a React Application

Sass was created several years ago and was originally implemented in applications built using Ruby. In recent years, it has been adapted to work with Node.js which is how we will be using it today. You may notice that we are creating “scss” files but calling it sass. This is because Sass was originally created with a certain syntax which is actually known as “Sass”. Later an alternative syntax was created to closer resemble CSS, and this is called “Scss”. Because Scss has the same functionality of Sass, it still falls into the category of Sass.

It is generally pretty simple to get up and running with Sass in a React js application, although it does make a difference how you go about bundling or compiling your application. In the code for this tutorial, I will be using Parcel js which is pretty easy to get up and running and handles the Sass for us. There are other libraries which are sometimes necessary such as node-sass, gatsby-plugin-sass, or next-sass.

Setting Up Our Sass Files

There are a few different ways to use Sass within a React js application. The first would be to create a component in a folder and include the styles for the component as a .scss file within that folder and import them directly into the component. I have done it this way and have found it to be easy but I didn’t care for the organization so much.

An alternative is to create a Sass folder within our project and this is where our styles will live. This is the organizational method we will be using today. That being said, we will create a folder in the project called “Sass” and add a file called “app.scss”. While we could put all of our styles into this app.scss file, that would get messy and wouldn’t provide much benefit over normal CSS.

Instead, we will create separate files and just import them into the app.scss file. We can then import the app.scss file into our app.js file and Parcel will do the rest.

Structure of Sass Folder

There are lots of different opinions on how to organize the folder with our styles. We could spend a TON of time going down a rabbit hole of organizational techniques, but I find that the way I like to do it is to organize my Sass folder the same as my project. Typically this would translate out to having the following layout:

  • Sass/
    • Components/ – A directory which has a .scss file for each React component
    • Pages/ – A directory which has a .scss file for each page that requires custom styles
    • Templates/ (optional) – A directory for templates if using them (for tools such as gatsby)
    • _elements.scss – Any generic styles for the site. Shouldn’t have any classes or ids for selectors.
    • _keyframes.scss (optional) – Any keyframes or animations I will be using for the site.
    • _mixins.scss – Any mixins (style snippets) that will be used over and over
    • _variables.scss – Any variables that will be used throughout styles
    • app.scss – The file that imports all other scss files

The first thing you may notice about the file names is that several of them start with an underscore. This is because outside of node, Sass is actually compiled to a CSS file. Any SCSS file without an underscore at the beginning is compiled as a different stylesheet. Since we are pulling all of our stylesheets into the app.scss file rather than separating them out, they should all start with an underscore.

Since our application is only one social media card, we won’t need all of these. For the sake of simplicity while explaining this, we will be using the app.scss, the _variables.scss, and the _elements.scss files as well as the components directory.

Styling React Using Sass | Usage | Application
Show Buttons
Hide Buttons