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.)
Installing styled-components
into our Gatsby project is an extremely easy two-step process.
For the first step, we just need to install three (required) dependencies from npm:
.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!
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.
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:
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.
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.
To keep things as simple as possible, let’s first create a basic ‘demo’ page at /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
}
}
}
`;
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.)
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.
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.
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.
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!