Extending Shadowed Files

Theme shadowing doesn’t just allow you to override entire files, like we’ve seen up to this point. After all, one of the issues with the CSS override example from the previous section is that you may not want such a small stylesheet to override every single line of CSS in the upstream file. Instead of overriding theme files, sometimes we need to extend those theme files through theme shadowing.

The primary method of extending shadowed files is to import the component you intend to shadow and then render it, in the process providing any additional information you want to include. Consider the following example adapted from the Gatsby documentation, which depicts a bio component that needs to pull from a theme’s components and extend them into a shadow component with extended functionality:

// src/gatsby-theme-blog/components/bio.js
import React from "react"
import { Avatar, MediaObject, Icon } from "gatsby-theme-blog"

export default function Bio({ name, bio, avatar, twitterUrl, githubUrl }) {
  return (
    <MediaObject>
      <Avatar {...avatar} />
      <div>
        <h3>{name}</h3>
        <p>{bio}</p>
        <a href={twitterUrl}>
          <Icon name="twitter" />
        </a>
        <a href={githubUrl}>
          <Icon name="github" />
        </a>
      </div>
    </MediaObject>
  )
}

In this example, all of the code within the <MediaObject /> component allows us to add to the theme’s default rendering of that component. If we didn’t extend the component in this way, we would instead need to copy the entire component from the upstream theme as a separate component in our site.

TIP

The previous example imports the components from the theme dependency, but you can also write more efficient code by importing the shadowed component into another component by referring to it directly, like this:

import {
  Author
} from "gatsby-theme-blog/src/components/bio"

Though theme shadowing is an effective way to use themes for more robust architectures in Gatsby, there’s always a risk of shadowing too much. As a best practice, if you’re finding that you’re overriding or extending a large number of files in the upstream theme, it might be a good idea to consider a fork of the theme instead and create a distinct theme. Gatsby officially supports this model by providing “core” themes, like gatsby-theme-blog-core, a dependency for gatsby-theme-blog, that can serve as foundations for forks of gatsby-theme-blog or new themes.

NOTE

For more information about leveraging shadowed components with distinct prop APIs in React, consult the Gatsby documentation. The documentation also contains a guide on how theme shadowing and theme composition operate under the hood.


Posted

in

,

by

Tags:

Comments

Leave a Reply

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