🎁

12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
05 : 09 : 47 : 50
1×
Become a member
to unlock all features
Autoplay

    Add Dark Mode to a Gatsby Site with Theme UI

    John OtanderJohn Otander
    reactReact
    gatsbyGatsby

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

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

    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.

    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.

    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.

    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.

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