For Dummies: Dark Mode with Gatsbyjs

When it comes to Gatsby, there are several unique hacks you should be aware of in order to successfully create a dark mode for your application.

HRブログ
Ageless Dynasty
4 min readOct 27, 2022

--

ChromeDevTools.gif

In this post, we will go through the whole implementation from start to finish.

Prerequisites

Getting started

Add the simple command below to create a new site.

💡 Note — Continue to follow the prompts to select your desired language (JavaScript or TypeScript), CMS, styling tools, and other features.

When everything has been downloaded, you will get a notice with instructions on how to navigate to your site and execute it locally.

💡 Note — Navigate to localhost:8000 and you should see your app running. Edit the home page in src/pages/index.js, save it, and reload the page to see your live changes in the browser.

Part 1: Adding CSS Variables

The aim is to use CSS variables and React’s UseState hook. Any alternative state manager will also work, but for the sake of simplicity, we’ll simply employ the standard UseState hook.

We’ll start building the CSS for dark mode.

💡 Note — By adding these variables to the body element, they become available to all of our components and classes globally.

Next, we’ll add values to the dark and light mode variables. We will accomplish this by defining a class.

💡 Note — We have now defined the themes for the light and dark modes.

Part 2: Adding a switch button for toggling between dark and light themes

We’ll have a toggle component that appears on all of our pages, hence it seems reasonable to have the switch button there.

Here’s what the toggle component looks like:

💡 Note — These icons function as buttons, and when selected, they either add or delete the .dark class from the body, changing the app's theme.

Devpost.gif

Part 3: Saving the default theme to the local storage

Now we also need to store the preferred mode to local storage, so that it will remain even if the page or application is reset. To accomplish this, I create a global utility function called getDefaultTheme:

💡 Note — This method must now be invoked within the useState hook created within my DarkMode component.

To do this, I return to the useEffect hook and insert the following code:

If you followed along, your completed code should look like this:

--

--

HRブログ
Ageless Dynasty

Talks about #realworld, #finance , #economics, #crypto and #technology.