Tutorial

Using styled-components in Gatsby

Published on July 10, 2019
author

Daniel Stout

Using styled-components in Gatsby

When creating a new Gatsby.js project, there are several available options for styling. We could write our own CSS/SCSS stylesheets, install frameworks like Bootstrap, and/or use various CSS-in-JS solutions. styled-components is one of the most popular CSS-in-JSS solutions, and for good reason. It’s powerful, easy to learn, and it works flawlessly with Gatsby. Let’s explore how to add it into your project!

This post assumes that you already have a working Gatsby.js project that is ready to edit. (If you need help with that, please follow the steps in Your First Steps with Gatsby v2 and then return here afterwards.)

Installation

Installing styled-components into our Gatsby project is an extremely easy two-step process.

1. Install the required dependencies:

For the first step, we just need to install three (required) dependencies from npm:

  • styled-components: The main styled-components framework, which is an extremely elegant and flexible CSS-in-JS solution built for React. It automatically handles SSR, auto-prefixing, and MUCH more. (See their fantastic documentation here: styled-components docs)
  • gatsby-plugin-styled-components: The official Gatsby.js plugin for styled components.
  • babel-plugin-styled-components: This is a plugin for Babel that provides more legible class names, server-side rendering ability, smaller bundle sizes, and more. (Gatsby depends on this, but we won’t have to make any manual edits to a .babelrc file.)

Let’s navigate to our project root directory, and run the following from the command prompt:

$ yarn add styled-components gatsby-plugin-styled-components babel-plugin-styled-components

Note: It’s ok to install these with npm, if you prefer using that!

2. Add the plugin to your Gatsby config:

For the second/final step, we add the plugin into our Gatsby configuration. In our project’s gatsby-config.js file, let’s add it to the plugins array.

gatsby-config.js
module.exports = {
  ...
  plugins: [
    {
      resolve: `gatsby-plugin-styled-components`,
      options: {
        // Change plugin default options here, e.g.:
        // ssr: false
        // displayName: false, 
        // minify: false
      },
    },
    //... other plugins
  ]
}

There are a few options available for overriding the default settings, such as disabling minification or server-side rendering. A complete list and description of these can be found here in the styled-components docs.

If you don’t plan on customizing the plugin options (and I rarely do), a quicker single-line approach also works:

gatsby-config.js
module.exports = {
  ...
  plugins: [
    `gatsby-plugin-styled-components`,
     //... other plugins
  ]
}

That’s all! styled-components is now installed and ready for use in our Gatsby project.

Usage

This post is not meant to be a detailed lesson in using styled-components, as that would be a lengthy post on its own! However, let’s create a few quick examples to demonstrate usage in our Gatsby project.

Create a new page

To keep things as simple as possible, let’s first create a basic ‘demo’ page at /src/pages/sc-demo.js.

/src/pages/sc-demo.js
import React from 'react';
import { Link, graphql } from 'gatsby';
import Helmet from 'react-helmet';

import Layout from '../components/layout';

class SCDemoPage extends React.Component {
  render() {
    const siteData = this.props.data.site.siteMetadata;
    const siteTitle = siteData.title;
    const siteDescription = siteData.description;

    return (
      <Layout location={this.props.location}>
        <Helmet
          htmlAttributes={{ lang: 'en' }}
          meta={[{ 
            name: 'description', 
            content: siteDescription 
          }]}
          title={siteTitle}
        />

        <section>
          <h2>Styled Components Demo</h2>

          <div>
            <h3>Banana Milkshakes</h3>
            <p>We'll definitely need frozen bananas 
            and some milk.</p>

            <Link to='/'>To Homepage</Link>
          </div>
        </section>
      </Layout>
    )
  }
};

export default SCDemoPage;

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
        description
      }
    }
  }
`;

Import and use styled-components

We’re just going to add some simple styles to our ‘Banana Milkshakes’ div. First, let’s import styled-components at the top of the page, right after the Helmet import line:

import React from 'react';
import { Link, graphql } from 'gatsby';
import Helmet from 'react-helmet';

import styled from "styled-components"; // 💅 yay!

Then, just under the Layout import line, let’s create two styled components. For the first one, CustomBox, we will create a component that applies styling to an HTML div element. (Notice the SASS-like nesting.)

const CustomBox = styled.div`
  border: 1px solid rgb(0, 143, 104);
  padding: 20px;

  h3 {
    color: rgb(109, 182, 91);
    margin: 0 0 10px;
    padding: 0;
  }
`

For the second one, we will apply styles to Gatsby’s Link component. This is to demonstrate that you can style nearly any component, not just HTML elements! (I’ve used it to tweak react-bootstrap components, for example.)

const StyledLink = styled(Link)`
  color: red;
`

Important: Note the use of [template literal strings](https://www.digitalocean.com/community/tutorials/js-template-literals-es6) in both items above! (Those are backticks, not single quotes.)

Use the new components inside the page

Now we can put these to use! First, let’s swap the plain div tag surrounding our Banana Milkshakes info with the new CustomBox tag. Then, replace the Link tag with the StyledLink tag.

And here is the result:

<CustomBox>
  <h3>Banana Milkshakes</h3>
  <p>We'll definitely need frozen bananas 
  and some milk.</p>
  <StyledLink to="/">To Homepage</StyledLink>
</CustomBox>

That’s it! If your Gatsby site is running in development mode, you’ll see the styles update immediately after saving.

Conclusion

Adding styled-components to your Gatsby.js project is not difficult, and can be a real game-changer. This demo barely scratches the surface, so I encourage you to dig deeper into the styled-components documentation to see all the amazing things it can do!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Daniel Stout

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


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!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more