Theming using CSS Variables - React JS

Anand B
2 min readFeb 11, 2021

Being a Web developer and a huge fan of the dark theme for the apps, I was always excited by how apps these days are smoothly switching themes. All of the apps on my phone and my laptop are running on dark mode. Still waiting for google.com to be in dark mode.

Jokes apart, I came across CSS Variables which helps in achieving the theme implementation easily. It is supported by all browsers so we can start using them like a pro. Simply put, it lets us create variables in a CSS file.

Reference: CSS Variables MDN

I have created a React Project for this implementation but this will be the same for any framework. Before we go into the actual implementation, below is the application behavior on the switching theme. If you see, only a parent div changes its class.

Theme Switching

My React project structure consists of App.js and I separated the Header into a different Component. The CSS Variables are maintained in App.css only and can be used throughout all the components in the app.

React Project Structure

The CSS Variables can be created in the different theme classes.

.lightTheme {--background: #ebebeb;--primary-Color: #F8D319;--secondary-Color: #F86A19;--text-Color: #000;}.darkTheme {--background: #252525;--primary-Color: #F86A19;--secondary-Color: #F8D319;--text-Color: #fff;}

The theme variables can be used in the relevant classes.

.CustomHeader {background: var(--primary-Color);color: var(--secondary-Color);text-align: center;align-items:center;font-weight: bold;width:100vw;height: 3rem;line-height: 3rem;font-size: calc( 16px + 2vmin)}

For switching the themes, I am changing the class of the parent div. The parent div‘s className property is bound with the theme variable.

let [theme, setTheme] = useState("darkTheme");const fnChangeTheme = () => {setTheme(theme === "darkTheme" ? "lightTheme" : "darkTheme");}

The whole source code can be found on codesandbox.io

CodeSandBox Link

Code Sandbox Preview

Hope you had fun. Until next time :)

--

--