Theming in React Native - Basics

The darker UI design trend has gained popularity over the past few years in response to increased user screen time across devices. It is no wonder you want to enable this feature in your application as well. This article will look at how this can be implemented in a React Native application.

Requirements

We will use the useContext hook provided by React Native to rerender the component when the theme changes. Apart from that, we will also need an event emitter to emit and listen for theme-change events. For that, we will use eventemitter3 - a package from npm.

Let’s first create constants that we will need going ahead.

First, we will create a context object which will store 2 fields.

  1. mode - a variable that will store the currently selected theme
  2. toggleTheme - a function that will be called to toggle the theme.

Then we will create a custom hook that will be used in the components which will enable switching between light and dark modes. And finally, a theme provider that will provide context throughout the application. The below code snippet shows its implementation

You will also need to wrap your App component inside  ThemeProvider like this.

function App() {
  return (
    <ThemeProvider>
        <MyApp/>
    </ThemeProvider>
  );
}
const styles = {
  container: {
    flex: 1,
  },
};

export default React.memo(App);

Now, we just need a controller that will return the color object according to the selected theme.

That's it. Now we can enable theming in any component. Let's create a component and see how it can be done.

The resulting component should look like this

In this way, you can achieve basic theming with light and dark modes in a React Native application. In the next article, we will discuss how to add multiple color themes each with light and dark modes. Stay tuned.

Harsh Siriah

Harsh Siriah

Hi, I'm Harsh! A geek with a love for dogs & mobiles.
Pune, India
Vinay Harwani

Vinay Harwani

Hi, I am Vinay. I am a software engineer particularly interested in mobile application and backend development.
Pune, India