Add Dark Mode to a Gatsby Site with Theme UI

John Otander
InstructorJohn Otander
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Theme UI has built-in color mode support that makes it straightforward to add a dark mode to your Gatsby project. You can use the useColorMode hook to retrieve the active color palette and set it to a predefined dark color palette.

Instructor: [00:00] The function in Gatsby and theme-ui site. The first thing we'll need to do is open up our theme file so we can add a new color mode. In addition to our existing colors, you can add a modes object where you can specify new color palettes under a name.

[00:14] We'll call this one dark, and essentially set the inverse of colors. There are dark color palettes set.

[00:23] We'll also want to add a name to our initial color palette. We'll use the initialColorModeName for this. We'll call it light.

[00:31] Now we can open up our layout file. We'll need to import the useColorMode hook from theme-ui. When we invoke the hook, we'll get back the colorMode and setColorMode. For now, let's go ahead and log out the colorMode.

[00:47] Since you know what the active color mode is, we'll now need to determine what the next one will be. We know that if the current color mode is light, the next one will need to be dark. We can go ahead and log this.

[01:02] Now we can create our button for toggling. We'll set its text to new color mode. With the button rendered we'll need to handle the onclick event.

[01:14] When the button is clicked, we'll go ahead and call setColorMode with newColorMode. There we go. We have dark mode and light mode.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today