Building a Personal Site with Gatsby

Part 2: Styling with SASS/SCSS

January 11, 2019

Note: This is a 9 part post that begins here: Part 1: Introduction and Setup

Gatsby doesn't prescribe a specific styling approach and I've chosen to use SCSS, but support is available for many approaches, which you can read about here: Gatsbyjs.org: Styling.

Using SASS/SCSS

The default template provides a src/components/layout.css file that is imported into src/components/layout.js but you can add support for SASS/SCSS by adding gatsby-plugin-sass .

Install node-sass and gatsby-plugin-sass.

shell
npm install --save node-sass gatsby-plugin-sass

Include the plugin in your gatsby-config.js file.

gatsby-config.js
module.exports = {
  siteMetadata: {
  // ...
  },
  plugins: [
    `gatsby-plugin-sass`,
  // ...
  ],
}

Create a src/styles folder with a file called styles.scss, and import this into your layout file.

src/components/layout.js
import React from 'react'
import PropTypes from 'prop-types'
import { StaticQuery, graphql } from 'gatsby'

import Header from './header'
import '../styles/styles.scss';

Add a src/styles/_button.scss file and add the following styles:

src/styles/_button.scss
.button {
  background-color: rgba(rebeccapurple, 0.7);
  color: white;
  cursor: pointer;
  font-weight: 700;
  padding: 1rem;
  text-transform: uppercase;
  transition: all 0.4s ease;
  &:hover {
    background-color: rgba(rebeccapurple, 0.9);
  }
}

Import your button partial into src/styles/styles.scss:

src/styles/styles.scss
@import 'button';

Create your Button component at src/components/button.js and add the following:

src/components/button.js
import React from 'react';

const Button = ({ buttonText }) => {
  return <button className="button">{buttonText}</button>;
};

export default Button;

Add your component to your src/pages/index.js file to test it out

src/pages/index.js
//...
import Button from '../components/button'
const IndexPage = () => (
  <Layout>
    <SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
    <h1>Hi people</h1>
    <Button buttonText="Click me" />    // ...
  </Layout>
)
// ...

...which will produce: