@studio_hungry Twitter@molebox GitHubRichard Haines LinkedIn

How to make a gatsby ecommerce theme. Part 1

Author: Richard Haines

Posted: 10 Mar 2020

We're going to go from start to finish and create a gatsby theme that you can deploy as an npm package. In the first part we will cover the base setup of the project.

This is part 1 in a series of tutorials. The format is step by step.

So where to start? You have an idea, you want to create an ecommerce theme for all the world to use. In this tutorial we are going to create a new gatsby theme from scratch, handle payments using snipcart, store our data with sanity.io and style it with theme-ui. Its going to be dope 😎

There are a few pre-requisits, Im going to assume you know how to use Gatsby and React to a certain degree, the rest we will walk through.

We are going to be building this from scratch so lets start by creating our new project

1mkdir gatsby-theme-fashion
2cd gatsby-theme-fashion

Cool beans, so lets now create our project. When working with gatsby themes i like to use yarn workspaces, this allows us to keep our theme and an example site in a monorepo with yarn controlling the dependencies between them. Lets create our projects root, we'll use the -y flag to auto fill the package.json stuff as we will be removing it all anyway.

1yarn init -y

Now that we have a package.json in our folder we can open our code editor and remove the auto filled stuff and add our own. We want to add the workspaces key and add our project folders. There are many ways of doing this and people have different opinions about which way is best. This is my preferred method.

package.json

1{
2 "private": true,
3 "workspaces": [
4 "demo",
5 "packages/*"
6 ]
7}

We want the project to be private as we wont publish it and also workspaces wont work if we don't set this. We have also specified that we will have one folder for our demo project and another which will hold our packages, or our theme(s).

Create the demo and packages folders

1mkdir demo
2mkdir packages

We'll start with our theme and hop over to the demo site a bit later on. Lets move into the packages folder and create our themes folder and initialize the project, following yarns instructions for setup as we go. I like to set the version to 0.0.1 from the start as during development we will be publish our package and when it comes time to release it in the wild its going to look strange if our version number is 54.9.7 or something. Keep it at the patches in development until release.

1cd packages
2mkdir gatsby-theme-fashion
3cd gatsby-theme-fashion
4yarn init

Now that we have our theme project installed lets add the base packages we are going to need. For us those are gatsby, react, react-dom, theme-ui, gatsby-plugin-theme-ui @emotion/core and @mdx-js/react. Lets also add prettier so that all our code looks pretty once we save it! 😇

1yarn add gatsby react react-dom theme-ui gatsby-plugin-theme-ui @emotion/core @mdx-js/react gatsby-plugin-google-fonts
2yarn add prettier -D

Niiiice! Cool, now lets add some scripts to our package.json for building, cleaning and making stuff pretty.

package.json

1"scripts": {
2 "dev": "gatsby develop",
3 "build": "gatsby build",
4 "clean": "gatsby clean",
5 "pretty": "prettier --write \"src/**/*js\""
6 },

You can give the keys whatever name makes sense to you. We'll be mostly using dev, clean and pretty. We could set up a pre commit hook to run pretty when we commit code, you can look that up, for this example we will skip it. I quite like typing out yarn pretty and watching all my code transform. You can also set it up to run on save in vscode, again, that is something for you to google.

We want to add gatsby, react and react-dom as peer dependencies so that the end user has to install them.

package.json

1"peerDependencies": {
2 "gatsby": "^2.19.8",
3 "react": "^16.12.0",
4 "react-dom": "^16.12.0"
5 },

Now we need to add our gatsby-config.js file and add the plugins we have installed for our theme. Its important to add the gatsby-plugin-theme-ui plugin at the end as it will be overriden by the theme consumer if they have it installed also.

gatsby-config.js

1module.exports = {
2 plugins: [
3 {
4 resolve: 'gatsby-plugin-google-fonts',
5 options: {
6 fonts: [
7 'Muli',
8 'Open Sans',
9 'source sans pro\:300,400,400i,700'
10 ]
11 }
12 },
13 'gatsby-plugin-theme-ui'
14 ]
15}

We have used gatsby-plugin-google-fonts so that we can easily install some nice fonts from google. Feel free to choose your own.

I should add at this point that the versions are explicit to this tutorial, everything should work regardless, that being said it can be that some breaking changes are introduced at some point in the future so yours may differ from mine, if you have any problems check the changelog from my version to the version you are using to debug the problem.

Ok so lets add some folders and files to our project.

1touch src/pages
2touch src/components
3touch src/pages/index.js

We also want to create an index.js file at the root of out theme as thats what gatsby is looking for

1touch index.js

Add a comment to this file so it has some content and we know whats going on. Later on we can if we like export some of our theme components from this file for the end use to import.

Sweet! We've got a really basic theme setup, it doesn't do anything right now, first we want to setup our demo site and link it to our theme. The magic of yarn workspaces!

1cd ..
2cd demo
3yarn init
4yarn add gatsby react react-dom dotenv

Your demo sites package.json should look something like this:

1{
2 "name": "demo",
3 "version": "1.0.0",
4 "main": "index.js",
5 "license": "MIT",
6 "scripts": {
7 "dev": "gatsby develop",
8 "build": "gatsby build",
9 "clean": "gatsby clean"
10 },
11 "dependencies": {
12 "dotenv": "^8.2.0",
13 "gatsby": "^2.19.8",
14 "gatsby-theme-fashion": "*",
15 "react": "^16.12.0",
16 "react-dom": "^16.12.0"
17 }
18}

We have added dotenv so that we can access the environment variables later on. We are also telling our demo site to use any version of our theme it finds. We have also added our scripts so that we can actually run the thing!

Next create a new file called gatsby-config.js at our demo projects root and add our theme as a plugin.

gatsby-config.js

1module.exports = {
2 plugins: ["gatsby-theme-fashion"]
3};

Right now we don't have any options that our theme requires so this will do. Then we run yarn from the root of our project to link it all up and we can then check if its all cool

1yarn
2yarn workspaces info

We should see the following output indicating that our demo site is linked to our theme:

1yarn workspaces v1.21.1
2{
3 "demo": {
4 "location": "packages/demo",
5 "workspaceDependencies": [
6 "gatsby-theme-fashion"
7 ],
8 "mismatchedWorkspaceDependencies": []
9 },
10 "gatsby-theme-fashion": {
11 "location": "packages/gatsby-theme-fashion",
12 "workspaceDependencies": [],
13 "mismatchedWorkspaceDependencies": []
14 }
15}
16Done in 0.06s.

BOOM!

So now might be a good time to commit our work. Go to github and login to your account and create a new repository called gatsby-theme-fashion. Then from the root of our project....

WHOA there ✋ Lets think about this for a second, we have just installed a bunch of packages, which means we have a node_modules folder at our root and in each project, thats a hell of a lot of files that we do not want git to see. Lets create our gitignore file at our projects root.

1touch .gitignore

Then add the following to it:

1node_modules/
2.env.*
3public/
4.cache/

Now i'll be honest, im not sure if you need to do this but i do it anyway, lets copy that file to our theme and demo projects.

Ok, nice! Now that thats done lets initialize our project with git and commit our work. You can get your remote repository url from the repository page you created.

1git init
2git add .
3git commit -m "My first commit"
4git remote add origin <remote repository url>
5git remote -v
6git push origin master
So lets recap what we have done so far:
  • Setup a project
  • Added our demo and theme projects
  • Linked our demo to our theme
  • Created a repository and committed our work

Now would be a good time to add some content and check that our theme is working. Head into your theme projects index.js file located inside src/pages folders and add a generic component to display an h1 that will render from our demo site as the imported theme.

1import React from 'react'
2
3export default () => <h1>Hello im coming at you from the theme!!<h1>

Go into your demo project and run gatsby dev. You should see a white page with the h1 text at the top left of the page, hurrah 🥳

Now that we have the base setup complete we can start thinking about what we want to have in our theme. As this is an ecommerce theme there are some basic things that we should consider before we continue. There will be a lot to add so lets get started!

  • Navbar
  • Landing/home page
    • Hero image
    • Showcase of products
    • Blog snippets
    • Instagram feed
    • Contact section
    • About section
  • Products page
  • Blog page
    • Blog posts page

These are some of the basic thing we expect an ecommerce site to have. There are of course a lot more thing we could add but lets keep it simple for our example theme. We will be keeping our layout fairly simple with a navbar at the top followed by a hero image and a section explaining about the store. Then a showcase of our top 3 most popular products followed by our Instagram feed and finishing off with our contact form in our footer.

We can begin by creating all the necessary pages:

1cd packages/gatsby-theme-fashion/src/pages
2touch products.js
3touch blog.js

Theme-ui will enable our end user to override some of our style with ease through shadowing our theme file which will hold all of our colours, fonts and spacings. In order to get started with adding our themeable variables we need to shadow the index.js file form the gatsby-plugin-theme-ui package in our src folder. See Theme-ui for more details.

I often start with the sites basic layout. There are a couple of ways to do this. We could create a layout component in our components folder with a css reset and import that into all or our components/pages but there is an easier way utilizing gatsby-plugin-layout.

Lets add that plugin

1yarn add gatsby-plugin-layout

Then we need to add it to our gatsby-config.js file:

gatsby-config.js

1module.exports = {
2 plugins: [
3 {
4 resolve: 'gatsby-plugin-google-fonts',
5 options: {
6 fonts: [
7 'Muli',
8 'Open Sans',
9 'source sans pro\:300,400,400i,700'
10 ]
11 }
12 },
13 {
14 resolve: 'gatsby-plugin-layout',
15 options: {
16 component: require.resolve('./src/layouts/index.js'),
17 },
18 },
19 'gatsby-plugin-theme-ui'
20
21 ]
22}

Create a layouts folder inside your src folder and add an index.js file. This will be our base layout for our site.

Layout

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import React from "react";
4import { Global, css } from "@emotion/core";
5
6const Layout = ({ children }) => {
7 return (
8 <>
9 <Global
10 styles={css`
11 * {
12 margin: 0;
13 padding: 0;
14 box-sizing: border-box;
15 }
16 body {
17 scroll-behavior: smooth;
18 overflow-y: scroll;
19 -webkit-overflow-scrolling: touch;
20 width: 100%;
21 overflow-x: hidden;
22 }
23 `}
24 />
25 <div>
26 {children}
27 </div>
28 </>
29 );
30};
31
32export default Layout;

This doesn't do much apart from reset some css and render the children within it. Lets create a basic grid layout using css grid. We are going to be using the theme-ui sx prop to add styling to our elements.

First up create some grid area strings as constants to be used in our grid. You can add these to a separate file if you wish but we will be adding them to the layout file in this example.

1const PhoneTemplateAreas = `
2 'nav nav nav nav'
3 'main main main main'
4 'footer footer footer footer'
5`;
6
7const TabletTemplateAreas = `
8 'nav nav nav nav nav nav'
9 'main main main main main main'
10 'footer footer footer footer footer footer'
11`;
12
13const DesktopTemplateAreas = `
14 '. nav nav nav nav nav nav .'
15 '. main main main main main main .'
16 '. footer footer footer footer footer footer .'
17`;

Then we can add these to the div that wraps our returned children in the layout component.

Layout

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import React from "react";
4import { Global, css } from "@emotion/core";
5
6const PhoneTemplateAreas = `
7 'nav nav nav nav'
8 'main main main main'
9 'footer footer footer footer'
10`;
11
12const TabletTemplateAreas = `
13 'nav nav nav nav nav nav'
14 'main main main main main main'
15 'footer footer footer footer footer footer'
16`;
17
18const DesktopTemplateAreas = `
19 '. nav nav nav nav nav nav .'
20 '. main main main main main main .'
21 '. footer footer footer footer footer footer .'
22`;
23
24const Layout = ({ children }) => {
25 return (
26 <>
27 <Global
28 styles={css`
29 * {
30 margin: 0;
31 padding: 0;
32 box-sizing: border-box;
33 }
34 body {
35 scroll-behavior: smooth;
36 overflow-y: scroll;
37 -webkit-overflow-scrolling: touch;
38 width: 100%;
39 overflow-x: hidden;
40 }
41 `}
42 />
43 <div
44 sx={{
45 display: "grid",
46 gridTemplateRows: "auto",
47 gridTemplateColumns: [
48 "repeat(4, 1fr)",
49 "repeat(6, 1fr)",
50 "repeat(8, 1fr)"
51 ],
52 gridTemplateAreas: [
53 PhoneTemplateAreas,
54 TabletTemplateAreas,
55 DesktopTemplateAreas
56 ],
57 padding: "0 1em"
58 }}
59 >
60 {children}
61 </div>
62 </>
63 );
64};
65
66export default Layout;

Lets breakdown whats going on here. I used to use Emotion css plus theme-ui to design and style my components, you can read about my experience here CSS grid with Theme-ui. Basically theme-ui allows us to specify breakpoints using an array syntax, so [mobile, tablet, desktop]. Pretty cool huh! Now we need to create our nav, main and footer components. All the sites amin content will live inside the main component, by using gatsby-plugin-layout we can just import main as a wrapper to tell gatsby that whatever component should be rendered inside this grid area.

Create a layout folder inside our components folder and add these three components:

Header

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3
4const Header = props => (
5 <header
6 sx={{
7 gridArea: "nav",
8 padding: "1em",
9 backgroundColor: "background",
10 color: "text",
11 height: "100%",
12 padding: [null, "2em", "2em"],
13 paddingTop: ["2em", null, null]
14 }}
15 >
16 {props.children}
17 </header>
18);
19
20export default Header;

Main

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3
4const Main = props => (
5 <main
6 sx={{
7 gridArea: "main",
8 backgroundColor: "background",
9 minHeight: "calc(100vh - 60px)",
10 paddingTop: ["2em", "60px", "60px"]
11 }}
12 >
13 {props.children}
14 </main>
15);
16
17export default Main;

Footer

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3
4const Footer = () => (
5 <footer
6 sx={{
7 gridArea: "footer",
8 display: "flex",
9 flexDirection: "column",
10 alignItems: "center",
11 justifyContent: "center",
12 backgroundColor: "background",
13 color: "text"
14 }}
15 >
16 <p
17 sx={{
18 color: "text",
19 fontFamily: "body",
20 fontSize: ["0.7em", "0.8em", "1em"],
21 letterSpacing: "text",
22 fontWeight: 400,
23 margin: "1em auto"
24 }}
25 >
26 This is my footer!
27 </p>
28 </footer>
29);
30
31export default Footer;

You may be wondering where the background colour is coming from... When using theme-ui we import all of our styles from one main index file. This file can be shadowed by the theme consumer and thus they can override whatever styles we have in there to change the look of the theme. Lets create that now.

Inside the src folder create a new folder called gatsby-plugin-theme-ui, inside that folder create a new file named index.js and add the following:

Our theme styles

1export default {
2 fonts: {
3 body: "Open Sans",
4 heading: "Muli"
5 },
6 fontWeights: {
7 body: 300,
8 heading: 400,
9 bold: 700
10 },
11 lineHeights: {
12 body: "110%",
13 heading: 1.125,
14 tagline: "100px"
15 },
16 letterSpacing: {
17 body: "2px",
18 text: "5px"
19 },
20 colors: {
21 text: "#FFFfff",
22 background: "#121212",
23 primary: "#000010",
24 secondary: "#E7E7E9",
25 secondaryDarker: "#545455",
26 accent: "#DE3C4B"
27 },
28 breakpoints: ['40em', '56em', '64em']
29};

These values can be accessed via the sx prop as seen above.

Lets add them to our layout to complete this part of the tutorial.

Layout

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import React from "react";
4import { Global, css } from "@emotion/core";
5import Header from "../components/layout/header";
6import {
7 PhoneTemplateAreas,
8 TabletTemplateAreas,
9 DesktopTemplateAreas
10} from "./../window/breakpoints";
11import Footer from "../components/layout/footer";
12
13const Layout = ({ children }) => {
14 return (
15 <>
16 <Global
17 styles={css`
18 * {
19 margin: 0;
20 padding: 0;
21 box-sizing: border-box;
22 }
23 body {
24 scroll-behavior: smooth;
25 overflow-y: scroll;
26 -webkit-overflow-scrolling: touch;
27 width: 100%;
28 overflow-x: hidden;
29 }
30 `}
31 />
32 <div
33 sx={{
34 display: "grid",
35 gridTemplateRows: "auto",
36 gridTemplateColumns: [
37 "repeat(4, 1fr)",
38 "repeat(6, 1fr)",
39 "repeat(8, 1fr)"
40 ],
41 gridTemplateAreas: [
42 PhoneTemplateAreas,
43 TabletTemplateAreas,
44 DesktopTemplateAreas
45 ],
46 padding: "0 1em"
47 }}
48 >
49 <Header>
50 navbar will go here
51 </Header>
52 {children}
53 <Footer />
54 </div>
55 </>
56 );
57};
58
59export default Layout;
So lets recap what we have done so far:
  • Setup a project
  • Added our demo and theme projects
  • Linked our demo to our theme
  • Created a repository and committed our work
  • Added a site layout
  • Added our theme styles

In the next part we will start adding our main content components and a backend to store our products. 😎

Edit this post on GitHub.Previous: CSS grid with theme-uiNext: How to make a gatsby ecommerce theme. Part 2