Mastering React: Build Switchable Dark Mode with Styled-Components

David Nienajadlo
3 min readFeb 28, 2024

--

Pic from Pexels

✨ Introduction

Hey! Today I’d like to show you how to build a switchable dark/light theme using Context API and Styled-Components. If you had read my previous article, you would know how to share common state variables using one provider. Let’s build something nice using knowledge from the previous lesson!

🚀 Building app theme context

First of all, we need to create a theme context similar to the one from the previous lesson. Let’s create it but just a little bit cleaner this time round.

Before we start doing the exact job, we need to create types of our Theme Context, Theme and Theme Mode.

types/theme.ts

Now we can create the exact context provider with the context consumer hook. Let’s go.

Theme Context and Provider

Okay, our theme context is ready, but what’s next? Now we need to install the styled-components dependency, create global app styles and provide it to the styled-components wrapper, and of course, create themes with specified colors. I’ll show you how to do it. Let’s create themes first.

Defined Themes

Okay, so we got to defined themes now so we just need to provide them to the styled-components wrapper.

Provided theme to the styled-components wrapper

Okay, perfect, now we got the theme provided to the styled-components provider and the changeMode function provided to children of our wrapper. Now we can add global styles using styled components to change globally defined colors. But to get a better experience with styled-components themes, just define the type of provided theme.

Declare styled-components theme type here

Okay, now it’s going to be the last two steps. Just define global styles like this.

GlobalStyles definition

And insert them into our theme provider. Now you can access the changeMode function and change the global theme.

Theme toggling example

🍟 Summary

Nice! Now your skills are rocketing. When you have understood the Context API, you can do really awesome thing with React apps.

The link to CodeSandbox with this example is here.

👍 Thank you

Hope you enjoyed this lesson. If you want to learn things this way just follow my profile!

--

--

David Nienajadlo

✨ JavaScript Developer, Modern Technologies Enthusiast