Create dark mode structure in React projects (using Tailwind CSS, Typescript, and Custom Hook)

Samir Mirzaliyev
3 min readMay 15, 2022

Hi guys! Today We’re going to learn how to make a dark mode component and structure.

The main technologies are React, Typescript, Context API, and Tailwind CSS. Once I just want to remind It’s not a tutorial about any of these technologies. That means you should already know well all of them.

At first, let’s make a SwitchTheme component that controlled our buttons and their functionality. But first, we should write the “class” keyword to the “tailwind.config.ts” file.

For now, just skip useDarkMode custom hook’s parts. I took SVGs from https://heroicons.dev/ it’s free you can use it from here or where you want it’s just a simple component.

Then we can go to the next step which we create Context for the theme. In my case, I just named ThemeContext.tsx but you can be named what you want. And of course, first I should create an interface for our Context.

After that, we can write our ThemeContext and don’t forget to give its types. But hold on, we should pass the first value to theme parameters that’s why I just write a simple function for that.

And now we already made our ThemeContext. We should create a new Provider component that always checks the current theme value and pass the theme and setTheme parameters to child components.

By the way, I just wrote Context and Provider in the same file.

Then we can write useDarkMode hook to make it easy.

As a result, we just wrap our main app component with the ThemeProvider and you can use the “dark” keyword in the component’s className prop.

Finally, we finished that. I hope it’ll help you and If you have any questions just text me anywhere you want. Goodbye, see you in the next article.

--

--