Add Dark Mode to a Gatsby Site with Theme UI

John Otander
InstructorJohn Otander

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year 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.

illustration for Theme UI

Course

Theme UI

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.