Changing color schemes in React Native based on dark and light modes

We've been working on integrating dark mode into an existing project, where specific colors are defined in a separate file and utilized throughout the application as shown below

import {Appearance} from "react-native";

const isDarkMode = (Appearance.getColorScheme() === 'dark')

const Color = {
    WHITE: '#FFFFFF',
    TRANSPARENT: 'transparent',
    THEMECOLOR: isDarkMode ? '#1A252F' : '#25A31D',
    THEMEBLACK: isDarkMode ? '#121B24' : '#252525',
    THEMEDARKGREEN: isDarkMode ? '#2F3F4D' : '#407F2C',
    THEMEWHITE: isDarkMode ? '#121B24' : '#FFFFFF',
    TXTGREETING: isDarkMode ? '#898989' : 'rgba(0, 0, 0, .5)',
    TXTWHITE: isDarkMode ? '#8A8A8A' : '#FFFFFF',
    TXTTHEME: isDarkMode ? '#676C69' : '#25A31D',
    TXTGREY: isDarkMode ? '#676C69' : '#9E9E9E',
    TXTDARKGREY: isDarkMode ? '#505050' : '#9E9E9E',
    TXTBLACK: isDarkMode ? '#676c69' : '#252525',
}

export default { Color };

The color values are then used like this

import appColors from "common/colors";

export default StyleSheet.create({
    container:{
        flex:1,
        backgroundColor: appColors.Color.THEMECOLOR,
    }
});

While our app does not have an internal switch for dark mode, it does automatically adjust based on the device settings. However, restarting the app is required for the changes to take effect.

We have encountered an issue when trying to implement themes in NavigationContainer during runtime

import { NavigationContainer,DarkTheme,DefaultTheme } from "@react-navigation/native";
render() {
    return (
      <NavigationContainer theme={isDarkMode?DarkTheme:DefaultTheme}>
        <RootStackScreen screenProps={this.props} />
      </NavigationContainer>
    )
}

If you have any suggestions on how to achieve seamless dark mode switching during runtime when the device settings change, we would appreciate your input.

Thank you!

Answer №1

I encountered a similar issue and managed to resolve it using the following code snippet:

const [selectedTheme, setSelectedTheme] = useState(() => Appearance.getColorScheme());

const handleThemeChange = useCallback((newTheme) => {
  setSelectedTheme(newTheme.colorScheme);
}, []);

useEffect(() => {
  Appearance.addChangeListener(handleThemeChange);
  return () => {
    Appearance.removeChangeListener(handleThemeChange);
  };
}, [handleThemeChange]);

Answer №2

Arthur's approach is spot on. Another option for manual switching is to include a button that stores 'light' and 'dark' values in ASync Storage, then fetches and loads them before rendering.

That's exactly what I've been doing! Manual buttons can definitely work, especially for users with older phones in our userbase.

You'll typically find Arthur's code in the file containing the Navigation Stack. For single-page apps, it should be loaded on the home screen.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an external JavaScript and CSS file for date picker in Eclipse can be done by following a few simple steps. By creating separate files for the

I am using the following javascript and css styles: <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jq ...

Count the number of checkboxes in a div

In my current project, I am working on incorporating three div elements with multiple checkboxes in each one. Successfully, I have managed to implement a counter that tracks the number of checkboxes selected within individual divs. However, I now aspire to ...

Why does async return an empty array the first time it is used?

I'm currently developing a JavaScript application using Node.js. I have been experimenting with the async/await function. After running the code snippet below, I noticed that the first time I send a GET request, I receive an empty array. However, if ...

JavaScript threw a SyntaxError: Unexpected character in line 1 while trying to parse JSON

I have a situation in Python where I load a variable with data and then convert it to JSON using the following code. jsVar = (json.dumps(jsPass)) This code produces the following output: {"TT1004": [[1004, 45.296109039999997, -75.926546579999993, 66.9966 ...

What is the best way to merge multiple statements into one before passing them into a JavaScript method?

I am faced with several javascript statements like the ones listed below: $('#' + xxx_slot_name1).children().remove(); $('#' + xxx_ad_slot_name2).children().remove(); $('#' + xxx_ad_slot_name3).children().remove(); $('#& ...

Send data from HTML forms to PHP without needing to reload the page

I’m currently developing a website that showcases data retrieved from a database using PHP. The site includes checkboxes within a form, and based on the user's selections, I want the data displayed in a certain div to refresh when they click ‘appl ...

How come TypeScript doesn't retain the positions and types of array elements in memory?

I am currently working on creating an array of objects that consist of questions, associated actions to perform (functions), and arguments to supply to the functions. I am facing issues with TypeScript not recognizing the types and arguments, and I would l ...

Comparison between instanceof and constructor.name

Background information: Currently, our application retrieves images from a GET API Accept: 'application/octet-stream', responseType: 'blob' and we utilize the following method to display the image on the user interface. let imageUrl ...

AngularJS Chrome Extension has been flagged as potentially harmful, despite the implementation of compileProvider.aHrefSanitizationWhitelist. This has resulted

I have previously shared this issue, however, the suggested solutions did not resolve it. Therefore, I am reposting with a more widely recognized solution: I am currently working on developing a chrome extension using AngularJS. In my base directive, I am ...

Tips for obtaining the combined outcome of multiple arrays (3 to 5 arrays) in JavaScript

How can we transform an array of objects with nested arrays into a new array of objects with mixed values? Consider the following input: var all = [ { name: "size", value: [20, 10, 5], }, { name: "color", value: [ ...

Binding textarea data in Angular is a powerful feature that allows

I am looking to display the content from a textarea on the page in real time, but I am struggling to get the line breaks to show up. Here is my current code snippet: app.component.html <div class="ui center aligned grid">{{Form.value.address}}< ...

The initial attribute unattainable for entities processed by csv-parse

Working on parsing a csv file, I am utilizing the csv-parse library to handle the following data - userID,sysID 20,50 30,71 However, after parsing, I am encountering difficulty accessing the property generated from the first column userID. Here is the s ...

Sorting an array of strings based on user input using Vue.js

I'm facing an issue where I have an array of various strings: [ "Aluminum", "Basic Materials", "Broad Credit", "Broad Market", "Cocoa", "Coffee", "Consumer Cyclicals", "Consumer Non-cyclicals", "Copper", "Corn", "Cotton", "Crude Oil", "Energy", "Exte ...

Tips for managing $rootScope in the provider's config function

Can someone help me understand how to work with $rootScope in a provider method? I'm unsure of how to properly inject it. that.app.config ['$authProvider', ($authProvider) -> $authProvider.configure apiUrl: '/api/v1&apos ...

Guide on implementing Vuetify Component Slot Function

Can someone help me figure out how to implement the v-alert dismissible component with additional functionality when the close button is clicked? According to the documentation, there is a function called toggle in the close slot that allows you to "Toggle ...

What is the best way to send FormData from a React JS axios post request to a Node server?

I am facing an issue where the form data is not reaching the node server even though it shows in the network payload at the time of request. Below are the snippets from different files involved in the process. let formData = new FormData(); // fo ...

iteration using underscores in JavaScript

I am currently working on creating an object using underscore and backbone. I have an array of objects, each containing a nested object with different sets of data. Within the array, data[0] holds the name of a location while data[2] contains the coordina ...

Click on a div to smoothly scroll to the top, then automatically scroll to the bottom if already at the top position

I've implemented a JQuery code on my website that allows the page to scroll to the top when clicking on a div with the class of .bottom. The code is working perfectly fine, here it is: function scrollToTop(){ $('.bottom').click(function ...

Is it possible to disable a function by clicking on it?

I currently have a website that is utilizing the following plugin: This plugin enables an image to be zoomed in and out through CSS transforms, with default controls for zooming in and out. My goal is to incorporate a reset button that returns the image ...

Using AngularJS - Injecting a variable into a directive's callback function

I need help with passing arguments from my directive to the caller. I've been struggling to make it work. Currently, I am able to call the function without any arguments successfully. However, when I try to pass arguments, it stops working: Here is ...