How to setup Theming in React app
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.