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.
- mode - a variable that will store the currently selected theme
- 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.
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.