First, we need to set up the environment. We are going to create a React Native App and then install the required packages.
The app will be named ReactNativeDarkMode, but you can put whatever you want as a name.
In your preferred terminal run the following command:
Redux is a predictable state container for Javascript apps. Because Redux can be used with many frameworks and libraries that's why along with redux we need to install react-redux.
Add the packages running the following command in your terminal:
React Navigation is a library that holds Routing and navigation for your React Native(RN) app. This library is being used by many developers lately. And personally I think it is robust and a great choice to hold Routing and navigation in RN. It´s also a great choice if you want to have a default theme in your app and apply it to all screens.
According to the official documentation, to install React Navigation we need to run the following commands:
React Native Appearance module has a known bug (Please check #28823) that cause change theme listener not working. In order to fix this bug we need to install another package called react-native-appearance
So we need to run the following commands:
Then, in order to have properly configured the Appearance module for React Native, we should modify the android/app/src/main/java/com/reactnativedarkmode/MainActivity.java file.
We need to add the following lines to the file:
Modify the App.js file with the following code:
In the App.js file add the following lines:
In the app root folder create the following file src/screens/HomeScreen.js, folders should be created as well.
In the HomeScreen.js file create a very simple functional component:
In the app.js file modify the file as follows:
export default App;
The Appearance module has an event listener that listens when the user or the system (scheduled color scheme change at sunrise or sunset) change the preferred color scheme. So we are going to add that listener when the application first starts in the App component.
To be more clear let's move the NavigatorContainerComponent to another new file. Create a new file src/NavigatorContainerComponent.js
Let's write the code for the new component:
First, we need to create a type that will be responsible for changing the theme. In order to do that we need the create a new file ./src/types.js and modify as following:
First, we need to pass the theme to the React Navigation Container, in order to do that we need to modify the src/NavigatorContainerComponent.js file as following:
DarkTheme and DefaultTheme have many properties that may help to be consistent using colors.
If you'd like to take a look at the complete code used in this post, head over to Francisco's GitHub project.
Ready to get started? Use the form or give us a call to meet our team and discuss your project and business goals.
We can’t wait to meet you!
Call us!
+1 (347) 871 09 22
Write to us!
info@vairix.com