3 Ways To Theme React Components

My favorite ways to theme React components.

Chidume Nnamdi 🔥💻🎵🎮
Bits and Pieces

--

In this post, I give a quick introduction to three of my top favorite ways to theming React components. When theming React components, we should take into consideration performance, ease-of-use (or developer experience), flexibility and “mobility” or how easy it is to reuse it in other projects.

For example, it’s quite common to see front-end teams publish their UI components to component hubs like Bit.dev. Unfortunately, publishing and documenting your components in component hubs is not enough for them to be easily reusable. A lot of consideration has to be taken into account — theming incorrectly can be detrimental to how much these components are actually being reused (and that, in turn, affects shipping time and UI consistency).

Exploring published React components in Bit.dev (a cloud component hub)

1. CSS Variables

CSS Variables or CSS custom properties are a way to set values in variables and refer to these variables, all with plain vanilla CSS.

To define a CSS variable globally, we commonly use the :root pseudo-selector (keep in mind, variables can be defined under any other CSS selector, but that means they will only be available to that selected group of elements).

Read more about “scoping” CSS variables here:

:root {
--css-variable: value;
}

The css-variable is the name of the CSS variable and value is its — you guessed it — value.

To define a CSS variable we append the double -- followed by the variable name.

:root {
--main-color: orangered;
}

Here, we set the main color of our app to be “orangered”. The main-color variable can be used as a value, anywhere in our style codes.

To use a CSS variable, we use a var(--css-variable-name) syntax. We pass the CSS variable name plus the -- to the var function, this will retrieve the value of the CSS variable --css-variable-name and set it to the property name.

:root {
--main-color: #1da1f2;
--background-color: #d7d7db;
}
button {
background-color: var(---main-color);
...
}
header {
background-color: var(--main-color);
...
}
body {
background-color: var(--background-color);
...
}

We have the variables --main-color and --background-color set to the color #1da1f2 (a sky-blueish color) and #d7d7db (ashen color), respectively. The background-color of the button and header will resolve to the value of the --main-color, #1da1f2 and the background color of the body will resolve to the value of --background-color, #d7d7db.

On execution, the style code would resolve to this:

button {
background-color: #1da1f2;
...
}
header {
background-color: #1da1f2;
...
}
body {
background-color: #d7d7db;
...
}

We can modify/update the CSS variables from JavaScript. We can get the value of CSS variables in a webpage by using the methods:

window
.getComputedStyle(document.documentElement)
.getPropertyValue(--css-variable-name)

and

document.documentElement.style.getPropertyValue(--css-variable-name)

Once we pass in the CSS variable name, the value is returned.

We can set the value of the CSS variable by using the method:

document
.documentElement
.style
.setProperty(--css-variable-name, value)

The setProperty needs the CSS variable name and the value to set it to as params. It then replaces the CSS variable name passed with the value.

document.documentElement.style.getPropertyValue("--main-color")-> reddocument.documentElement.style.setProperty("--main-color", "blue")document.documentElement.style.getPropertyValue("--main-color")-> blue

We have seen what CSS Variable is and how we can use it to build a re-usable style code.

Now, let’s see how we can use it to theme React components.

Let’s say we have a simple React app with an App component:

:root {
--main-color: #08e608;
}
#root {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
body {
color: var(--main-color);
}
.main {
width: 400px;
border: 2px solid var(--main-color);
padding: 3px;
}
button {
padding: 6px 12px;
background: var(--main-color);
color: white;
border: 1px solid transparent;
border-radius: 4px;
font-size: 16px;
margin: 2px;
}

The CSS variable --main-color holds #08e608 (“limegreen”) color. This will set the body color to #08e608, the button to #08e608 and the .main div borders to #08e608 color.

class App extends React.Component {
setTheme(color) {
if (color === "default")
color = "#08e608";
document
.documentElement
.style
.setProperty("--main-color", color);
}
render() {
return (
<div className="main">
<button onClick={() => this.setTheme("red")}>Set Theme(Red)</button>
<button onClick={() => this.setTheme("orangered")}>Set Theme(Orange-Red)</button>
<button onClick={() => this.setTheme("default")}>Reset Theme Default</button>
</div>
)
}
}

We have the App component here with three buttons. Each button when clicked calls the setTheme with a color. The setTheme method uses the setProperty to set the color of the --main-color.

The Set Theme(Red) button calls the setTheme with text "red", this sets the theme of the App component to "red".

The Set Theme(Orange-Red) button calls the setTheme with text "orangered", this sets the theme of the App component to "orangered".

The Reset Theme Default sets the component theme to the default color #08e608.

Serve the app npm run start and see the outcome:

Set the theme to “orangered” color

Set the theme back to the default theme:

View the source code here.

Let’s see another example, a Counter application with theme styling. You can play with the example in Bit’s playground here:

My React component themed using CSS vars, published on Bit.dev

More on theming React components with CSS Variables:

2. styled-components

styled-components uses CSS- in-JS to create a styled React component. style-components is simple and easy to use thanks to the relatively new Tagged Template Literals feature in JS (read more about it here).

import styled from "styled-components"const Button = styled.button`
padding: 6px 12px;
background: blue;
color: white;
border: 1px solid transparent;
border-radius: 4px;
font-size: 16px;
margin: 2px;
`
<Button>Click Me</Button>

styled-components will create a button component embedded with style:

padding: 6px 12px;
background: blue;
color: white;
border: 1px solid transparent;
border-radius: 4px;
font-size: 16px;
margin: 2px;

Now, we can create a variable to hold the border-color, background-color, main-color, etc to change the styled-components colors.

var borderColor = "red"
var backgroundColor = "blue"
var mainColor = "violet"
import styled from "styled-components"const Button = styled.button`
padding: 6px 12px;
background: ${backgroundColor};
color: white;
border: 1px solid transparent;
border-radius: 4px;
font-size: 16px;
margin: 2px;
`
<Button>Click Me</Button>

The background-color of the button is determined by the backgroundColor variable. Right now, the background color of the button is blue, if we change it to "red" the button background color will turn to — red (that’s, in a nutshell, what makes styled-component ideal for React).

styled-components provide us with a ThemeProvider. This ThemeProvider enables us to provide themes for React components as objects to any hierarchy in our component tree.

Let’s see an example:

import styled, { ThemeProvider } from "styled-components"const Button = styled.button`
padding: 6px 12px;
background: ${(props) => props.theme.bgColor};
color: white;
border: 1px solid transparent;
border-radius: 4px;
font-size: 16px;
margin: 2px;
`

Now our Button will be expecting a props theme, an object that will contain a property bgColor this will set the background-color of the Button.

class App extends React.Component {
constructor() {
super()
this.state = {
theme: {
bgColor: "violet"
}
}
}
setTheme(bgColor) {
this.setState({...this.state.theme, theme: { bgColor }})
}
render() {
return (
<ThemeProvider theme={this.state.theme}>
<Button onClick={()=> this.setTheme("red")}>Set Theme(Red)</Button>
<Button onClick={()=> this.setTheme("green")}>Set Theme(Green)</Button>
<Button onClick={()=> this.setTheme("violet")}>Set Theme Default</Button>
</ThemeProvider>
)
}
}

Play with the live demo in Bit’s playground here:

Note: I used my own version of styled-components in this example :). I will publish how I built it soonest.

My styled-components published and shared on Bit.dev

3. Descendant Combinator

In CSS we use combinators to affect parts of the HTML based on the selectors relationship. The relationship here is generally a parent-child, parent-grandchild, parent-greatgrandchild, parent-greatgreat~child kind of relationship.

One of them is the descendant combinator. This combinator enables us to style child elements contained in a parent element.

Descendant combinator would apply the styles no matter how deep a child element is in the parent element. The style would affect the child, grand-child, great-grand-child, ~ elements in the parent element. So, applying this to theming would be very ideal.

For example,

div h3 {
color: blue;
}

This will style all h3 elements inside a div element with color set to blue.

We can use class selectors or any other valid CSS selector types. Let’s see a class selector example:

.inner button {
color: red;
}

This rule will style all buttons contained in an element with class inner.

.theme {
color: white;
}
.theme-palevioletred .theme {
background: palevioletred;
}
.theme-blueviolet .theme {
background: blueviolet;
}

We have themes: theme-palevioletred and theme-blueviolet. If we apply .theme-palevioletred to an element class name, then all its child elements with .theme class name will have a palevioletred background. If we apply .theme-blueviolet to an element, then all elements with class name .theme will have a blueviolet background.

If we change a parent element class name from “.theme-palevioletred” to “.theme-blueviolet”, all the child elements with “.theme” will change their background color from palevioletred to blueviolet.

Let’s see a simple demo:

<html>
<head>
<title>Theming - Descendant Combinator</title>
<style>
button {
border-radius: 3px;
border: none;
padding: 2px 5px;
}

.theme {
color: white;
}
.theme-palevioletred .theme {
background: palevioletred;
}
.theme-blueviolet .theme {
background: blueviolet;
}
</style>
</head>
<body>
<div id="themeSet" class="theme-palevioletred">
<button class="theme" onclick="setTheme('theme-blueviolet')">Set Theme (blueviolet)</button>
<button class="theme" onclick="setTheme('theme-palevioletred')">Set Theme (palevioletred)</button>
</div>
</body>
<script>
function setTheme(theme) {
themeSet.classList.remove("theme-palevioletred")
themeSet.classList.remove("theme-blueviolet")
themeSet.classList.add(theme)
}
</script>
</html>

We have a div with class name “theme-palevioletred”, then, two buttons all with class name “theme”, all child elements of the div.theme-palevioletred. The two buttons will have a background color of palevioletred.

If we click on the “Set Theme(blueviolet)” button the class name “.theme-palevioletred” in the div will be removed and class name “blueviolet” will be added. This will make the two buttons background color to change to blueviolet.

In React, it will be like this:

button {
border-radius: 3px;
border: none;
padding: 5px 10px;
}
.theme {
color: white;
}
.theme-palevioletred .theme {
background: palevioletred;
}
.theme-blueviolet .theme {
background: blueviolet;
}
import React from 'react';
import "./ThemeSass.css"
export default class ThemeSass extends React.Component {
constructor() {
super()
this.state = {
theme: "theme-palevioletred"
}
}
setTheme(theme) {
this.setState({...this.state, theme })
}
render() {
return (
<div className={this.state.theme}>
<button className="theme" onClick={()=> this.setTheme("theme-blueviolet")}>Set Theme (blueviolet)</button>
<button className="theme" onClick={()=> this.setTheme("theme-palevioletred")}>Set Theme (palevioletred)</button>
</div>
)
}
}

The local state manages the current theme applied. The buttons will then update the state with a theme name when clicked to change the theming of the component.

Try the demo at Bit’s playground:

Check out my themed React component on Bit.dev

Conclusion

We have seen three ways by which we can theme our React components. They are very efficient and super simple to use.

If you have any questions regarding this or anything I should add, correct or remove, feel free to comment, email or DM me.

Thanks !!!

Learn More

--

--