React has become one of the most popular libraries for building robust applications, and styled-components is a powerful tool that enables developers to write CSS code within their React components. However, when using TypeScript with React, it can be challenging to maintain type-safety and consistency throughout your application’s styles. Theming allows you to write less code and maintain consistency with styling. Let’s see how to do that using styled-components with React and Typescript.
Let’s go to Theme.tsx, import ThemeProvider and write type and theme provider.
Second step is creating light and dark theme objects.
Now we have to create our Theme Provider and now we can set theme to “light” for the sake of simplicity.
We are using ThemeProvider from styled-components and setting attribute theme to our objects based on a condition.
In order to have access to the Theme everywhere in our codebase, we have to wrap our App with it.
It’s a common React pattern to have a wrapper component, often it’s called AppWrapper, AppProviders or Providers.
Now we can access to our theme across whole application. Let’s give it a try in App.tsx and create Wrapper component.
In order to toggle the theme we have to change theme variable in Theme.tsx which we hardcoded before to “light”. There are quite a few options to do that, in this post I’m going to create simple React context:
There we go, we have another provider in our codebase, let’s wrap our application by it in the AppProviders.
Whole application can consume the context so we can pass changeTheme function to a toggler which I created in App.tsx
The last step is to update Theme.tsx file with theme state from the context.
Now everything works and our theme is being changed!
If you enjoyed the read, you might consider checking out our FREE daily newsletter. We send short, 3 minute daily emails with
1 tip, 1 challenge and optionally news/tools from web development. Link ->