Theming System in React.js Way

Recently I got a request to let anyone outside the team can easily have their customised stylesheet applied to the platform we are working on. The most common way is to just insert another CSS file just below our original CSS to do the overwrite. However, since we are using React.js, this might a little too “not React-y”.

So we came up with a simple system that makes this possible.

Firstly, we create a ThemeManager component to be the wrapper and manager of themes:

ThemeManager should normally be inserted into the very last of the root component:

Then we simply create our own theme components, say “light” and “dark”:

The two theme components here is just to make sure we are able to dynamically include only the theme styles we need.

And now you can design your CSS for the theme, here I’d like to take the light theme as example:

The directory structure might look like this:

With the system above, every time you pass your theme prop from the root component to the ThemeManager, it’ll dynamically render the corresponding styles into the HTML document:

We use decorators to separately apply styles to the component, you can do it your own way.

Special thanks to my colleague @TaopaiC to brainstorm for the solution together.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.