Theme Shadowing in gatsby-theme-blog

To begin, let’s create a new site based on the Gatsby blog theme starter, which will automatically set up what we need:

$ gatsby new gtdg-ch10-theme-shadowing gatsbyjs/gatsby-starter-blog-theme

Once you’ve installed the starter, change directories into the scaffolded site. You’ll encounter an internal directory structure that looks like the following:

gtdg-ch10-theme-shadowing
├── content
│   ├── assets
│   │   └── avatar.png
│   └── posts
│       ├── hello-world
│       │   └── index.js
│       └── my-second-post.mdx
├── src
│   └── gatsby-theme-blog
│       ├── components
│       │   └── bio-content.js
│       └── gatsby-plugin-theme-ui
│           └── index.js
├── .gitignore
├── .prettierrc
├── gatsby-config.js
├── LICENSE
├── package-lock.json
├── package.json
└── README.md

As you can see, in our src directory, we have a gatsby-theme-blog directory containing just a few files, namely bio-content.js and colors.js. These are files that shadow, or override, the identically named files found in the theme plugin itself. If you were to open the node_modules directory containing the installed theme, you would see the unshadowed versions of those files as well as other shadowable files from the theme.

Open src/gatsby-theme-blog/components/bio-content.js, where you’ll find the following code:

// src/gatsby-theme-blog/components/bio-content.js
import React from "react"
import { Themed } from "theme-ui"

/**
 * Change the content to add your own bio
 */

export default function Bio() {
  return (
    <>
      This is where <Themed.a href=>your name</Themed.a>
      {` `}
      goes.
      <br />
      Or whatever, you make the rules.
    </>
  )
}

With this bio-content.js component shadowing the bio-content.js component in our installed plugin, we can now rewrite the file to our heart’s content to provide the specific bio we want to provide instead. This will override the logic in the upstream theme’s file and apply the custom logic we’ve written in the shadowed component. As you can see, any JavaScript component within a theme can be shadowed. But what about other files, like files provided by a theme’s dependency rather than the theme itself?


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *