Guide to an auto light theme in React with styled-components and typescript
This project was bootstrapped with Create React App. In the project directory, you can run: Runs the app in the…
I am pretty sure that a lot of people, including me, are huge fans of color theming. Although every single device that I own is set to the dark mode I love that feeling of being able to choose rather than being forced to use that bright white theme at the 3:48 AM day before the release. (I love you stripe ❤)
I’m not going to go in depths with context, typescript, or styled-components, I will just guide you through one of many solutions that I find comfortable using.
Let’s start by creating the app first. I’m going to do the minimal setup of the project, that said I’m just going to use the good old “create-react-app”.
If you don’t trust me about this part just go through the docs or skip the next part.
$ npx create-react-app auto-theme --template typescript
I sincerely suggest you using eslint and prettier with typescript because it’s a killer combo.
As far as styled-components are concerned I’ll follow through their official documentation as well.
You start by adding
$ yarn add styled-components
And because we’re doing this with typescript we’re going to have to add types as well.
$ yarn add -D @types/styled-components
Okay, so you should’ve ended up with something like this
Now we’ll be removing the CSS files and that test, you can just paste the command in the root of your project and it’ll do it for you.
$ rm -rf src/App.css src/App.test.tsx src/index.css src/logo.svg
Go ahead and create the
GlobalProvider.tsx in the
/src/theme/ like this.
Now we’ll make the theme instances.
To extend the “DefaultTheme” and get the autocomplete through all of the styled-components, we’re going to have to re-declare the module itself and extend the “DefaultTheme” with the type of our custom theme which I exported from the
The next step would be creating a declarations file, I did it in the root and called it
As soon as you include the
styled-components.d.ts in the
tsconfig.json you’ll have perfect autocomplete whenever you try to use your theme.
Okay, so I think that its the perfect time to deal with the provider, now that we took care of the default theme type.
Starting, I’m going to create a
And make a new
GlobalProvider component which is a wrapper providing the
GlobalContext to the whole application.
The main part of the code lies in the matchMedia method which with the right query can return the object based on which we can determine the users preferred theme and set the initial one to match the preferred.
And here is the final
The next step is wrapping the
App in the
index.tsx in the
As far as the switch button is concerned just make a standard component, use the
GlobalContext in which we stored the theme and the change fn and use it anywhere in the scope of the context provider.
And that’s it, you have successfully made an auto theme feature.