How to setup Theming in React app

Nelly Hovhannisyan
Preezma Software Development Company
2 min readSep 9, 2020

Hi, workaholics ! šŸ‘‹
Nowadays it is important to have theming in an application as it results a better user experience.
Now letā€™s setup theming in React application in a very simple way.

Requirements

In order to setup theming in a React application we need the styled-components to be installed.

Note: It is required to create React app first, if you donā€™t have it already, please follow React Get Started guide ā˜› https://reactjs.org/docs/getting-started.html.

Note: there are different ways to implement theming in a React application but we are going to implement it using styled-components as it is widely used in React applications.

What is styled-components?

Styled-components is a library for React and React Native which allow us to use technique called CSS-in-JS in our app. It let us write simple CSS in components without worrying about class name conflicts.

More details can be found in this article.

Letā€™s get started

First we need to install styled components:

// with npm
npm install --save styled-components

// with yarn
yarn add styled-components

Now letā€™s create a file called ā€œTheme.jsā€ in root directory, in which we are going to use ā€œThemeProviderā€ to provide theme to the child components.
In our example we are going to have light and dark theme variants.

For each theme variant we need to create theme object with the same exact keys. lightTheme is the theme object of the light variant and darkTheme is the theme object of the dark variant.

The ThemeProvider accepts the ā€œthemeā€ prop which get the theme and provides the theme properties to child components. The Theme component accepts ā€œthemeModeā€ from the parent component which specifies the theme mode to the ThemeProvider, if it should be light or dark mode (in our example).

We need to import Theme component in App.js and render child component(s) in it to make theme available in child component(s).

App.js
We need to have a local state for changing the theme mode from child component(s).
In this example ā€œchangeThemeModeā€ method is responsible for switching between light and dark theme modes.

Content.js
In Content component we have access to the theme that is provided by ThemeProvider and we can use it inside styled-components (example NewCard)

Demo

Source code is available in github.

--

--

Nelly Hovhannisyan
Preezma Software Development Company

Iā€™m Front-end developer I am a highly motivated, energetic and well organized and interested in collaborating in different projects .