UI Themes in React with Styled Components
In this story, we will explore how to manage UI themes in React app that uses styled-components on an example of pomodoro.increaser.org app.
First, we need an object that will represent a default theme. It will contain the most basic properties, such as colors, shadows, and transitions.
All of the themes are based on the default one, with slight changes such as background color or primary color. So it would be nice to have a function that will receive default theme and custom properties and will return a new theme. We assume that objects have only one layer of nesting.
To create additional themes, we make an array of objects, where each object contains the name of the theme and set of unique properties. Then we go over each object and call a mergeInfo function to receive a custom theme.
We will keep a theme in the redux state. On the start of the app, we take the name of the theme from the local storage if it is there. When a user selects a particular theme, we search it by name in the list of all themes and return a new state with an updated theme.
Now, when we have a theme in a redux state, we need to wrap root components with the theme provider, so that all styled components that rendered down the tree will have access to the theme.
With this approach, you can easily integrate different UI themes in your app. In the snippet below, you can find small functions that were used in examples.
Reach the next level of focus and productivity with increaser.org.