Coder Social home page Coder Social logo

expo / react-native-appearance Goto Github PK

View Code? Open in Web Editor NEW
337.0 3.0 41.0 685 KB

Access operating system appearance information (currently only light/dark mode) on iOS, Android, and web

License: MIT License

JavaScript 5.73% TypeScript 28.16% Java 29.12% Objective-C 26.13% Ruby 8.78% Starlark 2.07%

react-native-appearance's Introduction

react-native-appearance

Access operating system appearance information on iOS, Android, and web. Currently supports detecting preferred color scheme (light/dark).

⚠️ Appearance in React Native core is recommended unless you have a good reason to use the library (eg: you're on an older React Native version.) This project is archived now that it will not be needed going forward.

Installation

Installation instructions vary depending on whether you're using a managed Expo project or a bare React Native project.

Managed Expo project

This library is supported in Expo SDK 35+ (SDK 35 includes iOS support, SDK 36 and higher includes support for all platforms).

expo install react-native-appearance

Then, in app.json, include "userInterfaceStyle" to listen to the device's appearance settings:

{
  "expo": {
    /*
        Supported user interface styles. If left blank, "light" will be used. Use "automatic" if you would like to support either "light" or "dark" depending on device settings.
      */
    "userInterfaceStyle": "automatic" | "light" | "dark"
  }
}

Android support and web support are available on SDK36+.

Bare React Native project

yarn add react-native-appearance

Linking

If you are not using AndroidX on your project already (this is the default on React Native 0.60+, but not on lower versions) you will want to use the jetifier npm package. Install the package with yarn add -D jetifier and then under scripts add "postinstall": "jetify -r". Next run yarn jetify.

After installing the package you need to link the native parts of the library for the platforms you are using. The easiest way to link the library is using the CLI tool by running this command from the root of your project:

react-native link react-native-appearance

If you can't or don't want to use the CLI tool, you can also manually link the library using the instructions below (click on the arrow to show them):

Manually link the library on iOS

Either follow the instructions in the React Native documentation to manually link the framework or link using Cocoapods by adding this to your Podfile:

pod 'react-native-appearance', :path => '../node_modules/react-native-appearance'
Manually link the library on Android
  1. Open up android/app/src/main/java/[...]/MainApplication.java
  • Add import io.expo.appearance.RNCAppearancePackage; to the imports at the top of the file
  • Add new RNCAppearancePackage() to the list returned by the getPackages() method
  1. Append the following lines to android/settings.gradle:
include ':react-native-appearance'
project(':react-native-appearance').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-appearance/android')

  1. Insert the following lines inside the dependencies block in android/app/build.gradle:
implementation project(':react-native-appearance')

Configuration

iOS configuration

In Expo managed projects, add ios.userInterfaceStyle to your app.json:

{
  "expo": {
    "ios": {
      "userInterfaceStyle": "automatic"
    }
  }
}

For bare React Native apps, run npx pod-install. You can configure supported styles with the UIUserInterfaceStyle key in your app Info.plist.

Android configuration

Add the uiMode flag in AndroidManifest.xml:

<activity
...
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode">

Implement the onConfigurationChanged method in MainActivity.java:

import android.content.Intent; // <--- import
import android.content.res.Configuration; // <--- import

public class MainActivity extends ReactActivity {
  ......

  // copy these lines
  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Intent intent = new Intent("onConfigurationChanged");
    intent.putExtra("newConfig", newConfig);
    sendBroadcast(intent);
  }

  ......
}

Usage

First, you need to wrap your app in the AppearanceProvider. At the root of your app, do the following:

import { AppearanceProvider } from 'react-native-appearance';

export default () => (
  <AppearanceProvider>
    <App />
  </AppearanceProvider>
);

Now you can use Appearance and useColorScheme anywhere in your app.

import { Appearance, useColorScheme } from 'react-native-appearance';

/**
 * Get the current color scheme
 */
Appearance.getColorScheme();

/**
 * Subscribe to color scheme changes with a hook
 */
function MyComponent() {
  const colorScheme = useColorScheme();
  if (colorScheme === 'dark') {
    // render some dark thing
  } else {
    // render some light thing
  }
}

/**
 * Subscribe to color scheme without a hook
 */
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
  // do something with color scheme
});

// Remove the subscription at some point
subscription.remove();

Attribution

This was mostly written by Facebook for inclusion in React Native core.

react-native-appearance's People

Contributors

anhtuank7c avatar bbarthec avatar brentvatne avatar bycedric avatar dependabot[bot] avatar dylancom avatar ericp3reira avatar evanbacon avatar ide avatar jonsamp avatar mikehardy avatar movibe avatar mrbrentkelly avatar sasweb avatar tsapeta avatar yilinjuang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-native-appearance's Issues

theme is not changing when using useLayoutEffect

Hello,

I have this code in a screen:

import { useTheme } from "@react-navigation/native";
const { colors } = useTheme();
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Text styles={color: colors.text}}>TEST
),
});
}, [badge]);

If I go and change the iPhone settings to dark or light, the text does not change unless i refresh the page or hot reload when using expo, how can i solve it, everything is working perfectly except such thing

SSR rendering support with Expo & NextJS

I encountered an issue with the current web implementation that breaks the server side rendering part when using Expo and NextJS. It's related to the check if window.matchMedia is available or not. When running on the server, widow is undefined and will throw an ReferenceError: window is not defined error. We can fix it by checking if window is available or not, I'll propose a PR.

Can not debug remotely.

I bumped into this error while trying to debug remotely.
Screen Shot 2019-09-04 at 11 34 05 am

The library works fine when remote debugging is turned off.
"react": "16.8.3"
"react-native": "^0.59.6"

Android 10 support

Android 10 was reently released with dark theme support like iOS 13.

Is their any plans to also support android?

Appearance does not force style in modal

Appearance does not force style in modal

I have set color sheme to dark in app.json

{
  "expo": {
       "ios": {
           "userInterfaceStyle": "dark",

but in Modal keyboard steel light (as set in IOS user settings)
Alt text

but in whole app (not in modals) - it is truly dark (as setup in app.json)
Alt text

Android restarts on theme switch within Expo environment

Hi 👋 Thanks for the great work on this library and Expo support.

I'm sorry if I've missed something, but is it correct that Android completely restarts an app on a system theme switch while iOS is not forced to do this?

Related code:

const createAppearanceTheme = (appearance: ColorSchemeName, initialTheme: Theme): ColorSchemeName => {
  if (appearance === 'no-preference') {
    return preferredTheme;
  }
  return appearance;
};

export const useTheming = (initialTheme?: ColorSchemeName = 'no-preference') => {
  const deviceAppearance: ColorSchemeName = Appearance.getColorScheme();
  const deviceAppearanceTheme = createAppearanceTheme(deviceAppearance, preferredTheme);

  const [currentTheme, setCurrentTheme] = React.useState(deviceAppearanceTheme);

  React.useEffect(() => {
    const subscription = Appearance.addChangeListener((preferences: AppearancePreferences): void => {
      const appearanceTheme: ColorSchemeName = createAppearanceTheme(preferences.colorScheme, initialTheme);
      setCurrentTheme(appearanceTheme);
    });

    return () => subscription.remove();
  }, []);
};

Also "userInterfaceStyle": "automatic" in app.json

Which is followed by default configuration of usage docs

Demo

build error

Hello I constantly get the following error while build in latest version,

> Configure project :react-native-appearance WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'. It will be removed at the end of 2019. For more information, see https://d.android.com/r/tools/task-configuration-avoidance. To determine what is calling variant.getJavaCompile(), use -Pandroid.debug.obsoleteApi=true on the command line to display more information.

Can this package only be used from typescript?

When I install this package, I only get ts and tsx files in node_modules/react-native-appearance, and various tools (e.g. ESLint) throw errors like Unable to resolve path to module 'react-native-appearance'.

Can this package only be used in typescript projects?

Dark style not applying to google maps tiles

I'm not sure if this is an issue with react native maps (but I made an issue there a couple days, and haven't gotten a respond yet) or with react native appearance, or expo, or something else. Feel free to close if this issue isn't rooted in this repo.

I'm using React Native Maps, which serves up Apple Maps tiles on iOS devices, and Google Maps tiles on Android devices. On iOS, when you have dark mode enabled, the Apple Maps tiles change to night style. But on Android, they remain in day time style.

Dark mode does not work on vivo v15 (FunTouch OS)

Android version 9.0

It's how I use it, and it works fine on iOS and some android devices, I've only noticed that it does not work on vivo v15 device

const scheme = useColorScheme();
return (
  <AppearanceProvider>
    <NavigationContainer theme={scheme === 'dark' ? DarkMode : LightMode}>
      <AppStack />
    </NavigationContainer>
  </AppearanceProvider>
);

Release 0.2.0-rc.0 only works with RN0.60 (androidx) [FIX INCLUDED]

We are not using androidX yet and we're getting this error while compiling:

> Task :react-native-appearance:compileDebugJavaWithJavac FAILED
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCAppearanceManager.java:3: error: cannot find symbol
import android.annotation.NonNull;
                        ^
symbol:   class NonNull
location: package android.annotation
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperancePackage.java:3: error: cannot find symbol
import android.annotation.NonNull;
                        ^
symbol:   class NonNull
location: package android.annotation
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperanceModule.java:11: error: cannot find symbol
import android.annotation.NonNull;
                        ^
symbol:   class NonNull
location: package android.annotation
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperanceModule.java:12: error: cannot find symbol
import android.annotation.Nullable;
                        ^
symbol:   class Nullable
location: package android.annotation
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCAppearanceManager.java:10: error: cannot find symbol
    @NonNull
    ^
symbol:   class NonNull
location: class RNCAppearanceManager
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCAppearanceManager.java:18: error: cannot find symbol
    protected RNCAppearanceProvider createViewInstance(@NonNull ThemedReactContext reactContext) {
                                                        ^
symbol:   class NonNull
location: class RNCAppearanceManager
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCAppearanceManager.java:16: error: cannot find symbol
    @NonNull
    ^
symbol:   class NonNull
location: class RNCAppearanceManager
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperancePackage.java:17: error: cannot find symbol
    public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
                                                ^
symbol:   class NonNull
location: class RNCApperancePackage
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperancePackage.java:15: error: cannot find symbol
    @NonNull
    ^
symbol:   class NonNull
location: class RNCApperancePackage
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperancePackage.java:25: error: cannot find symbol
    public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
                                                ^
symbol:   class NonNull
location: class RNCApperancePackage
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperancePackage.java:23: error: cannot find symbol
    @NonNull
    ^
symbol:   class NonNull
location: class RNCApperancePackage
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperanceModule.java:31: error: cannot find symbol
    public RNCApperanceModule(@NonNull ReactApplicationContext reactContext) {
                            ^
symbol:   class NonNull
location: class RNCApperanceModule
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperanceModule.java:47: error: cannot find symbol
    @NonNull
    ^
symbol:   class NonNull
location: class RNCApperanceModule
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperanceModule.java:82: error: cannot find symbol
    @androidx.annotation.Nullable
                        ^
symbol:   class Nullable
location: package androidx.annotation
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperanceModule.java:90: error: cannot find symbol
    private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
                                                                        ^
symbol:   class Nullable
location: class RNCApperanceModule
/path/to/app/node_modules/react-native-appearance/android/src/main/java/com/reactlibrary/RNCApperanceModule.java:100: error: cannot find symbol
    private void sendEvent(String eventName, @Nullable WritableMap params) {
                                            ^
symbol:   class Nullable
location: class RNCApperanceModule
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
16 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-appearance:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

For those whom want an easy fix, use the patch file:
https://gist.github.com/nschild/0c9ded2e04af98054aca27d6359a2947

Also, add the following line to your build.gradle's dependencies section:
implementation 'com.android.support:support-annotations:+'

`tsc` error when `--isolatedModules` flag is provided

Using this with typescript works fine so long as you are not using the --isolatedModules flag. The moment that is set to true I get the following three typescript errors:

node_modules/react-native-appearance/src/index.tsx:21:3 - error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided.

21   ColorSchemeName,
     ~~~~~~~~~~~~~~~

node_modules/react-native-appearance/src/index.tsx:22:3 - error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided.

22   AppearanceListener,
     ~~~~~~~~~~~~~~~~~~

node_modules/react-native-appearance/src/index.tsx:23:3 - error TS1205: Cannot re-export a type when the '--isolatedModules' flag is provided.

23   AppearancePreferences,

It would be great if this were updated to include support for the isolatedModules flag! Thank you and please let me know if I can provide any further information!

How does Appearance.addChangeListener work?

I am not sure i can get it to work. I did Appearance.addChangeListener in my componentDidMount and have a state update inside of it but when I change the theme while testing nothing really happens and the colorScheme continues to have the previous colorScheme value. I am not sure if I am doing this correctly.

componentDidMount(){
   this._schemeSubscription = Appearance.addChangeListener(({ colorScheme }) => {
            this.setState({ colorscheme: colorScheme });
        });
}

useColorScheme only updates when putting the app into the background and then foreground.

On my Android device, when i change the system theme via the pull-down menu i have to put my app into the background and then foreground in order to see the Appearance ~> useColorScheme API update.

Is this expected behaviour?

function Root() {
    const scheme = useColorScheme();
    useEffect(() => {
        Appearance.addChangeListener((appearance) => {
            console.log("appearance", appearance);
        })
    }, []);
    console.log("scheme", scheme);

    return (
        <ThemeProvider theme={scheme === "dark" ? Theme.dark : Theme.default}>
            <NavigationContainer theme={scheme === "dark" ? Theme.dark : Theme.default}>
                <SplashScreen>
                    <AuthView />
                </SplashScreen>
            </NavigationContainer>
        </ThemeProvider>
    );
}
...
function App() {
    return (
        <AppearanceProvider>
              <Root />
        </AppearanceProvider>
    );
}

"scheme" & "appearance" logs only fire when the App comes into the foreground from being in the background when i am expecting the logs to fire as soon as the system theme is changed.

Appearance.getColorScheme() returns 'no-preference' on appcenter builds

Hello,
Does anyone else have this issue?

I am calling Appearance.getColorScheme() and getting no-preference
It works correctly on debug builds, but with builds built on AppCenter, it is not.

React Native 0.59.2
iPhone XR - iOS 13.2b4

Some psuedo code:

index.js

import { AppRegistry } from 'react-native';
import App from './app';
import { name as appName } from './app.json';

const appRoot = App;
AppRegistry.registerComponent(appName, () => appRoot);

app.tsx

import { Component } from 'react';
import { Appearance, AppearanceProvider } from 'react-native-appearance';
import ReactNativeRestart from 'react-native-restart';
import { Text, Alert } from 'react-native';

interface AppProps {}

export default class App extends Component<AppProps> {
  componentDidMount(){
    Appearance.addChangeListener(() => {
        ReactNativeRestart.Restart();
    });
    setInterval(() => {
        Alert.alert(Appearance.getColorScheme());
    }, 1000);
  }
  render() {
    return <AppearanceProvider><Text> Hello World</Text></AppearanceProvider>;
  }
}

URGENT!! Appearance.addChangeListener() is not calling after change phone mode in iOS

Hi,
I am facing an issue. Appearance.addChangeListener() is not calling after change phone mode (from dark to light and vice versa) from phone settings in iPhone. Please take a look into it urgent basis as my app is about to go on production and my clients are waiting for the app.

Environment used -
iPhone 8, iOS version 13.6.1
react-native-appearance : 0.3.4
react-native : 0.59.10
node version : 12.18.0
npm version : 6.14.4
mac os version : 10.15.5
xcode version : 11.6

Pod install does not work

Installing this module from a podfile does not work. There are no version tags in the repo for the git clone step. Please add a version tag, at least for 0.3.3

React Native's SegmentedControlIOS colour

Hi, everyone,

I recently started using this package when adding a theme to my app (based on React Navigation's Theme documentation). It's working fine but I've noticed an issue with React Native's SegmentedControlIOS component and I don't know if it's an issue with this package, React Navigation, or with that component itself.

As I haven't yet written my dark theme, I set my app to display the light theme regardless of whether the device was in dark mode or not. For the sake of testing, my custom light theme just consisted of the default values recommended, i.e. primary, background, etc. This meant that nothing should have changed (visually) when switching my phone between light and dark mode.

What I noticed, though, is that the SegmentedControlIOS still changed its appearance when the phone was set to dark mode. Here are screenshots to show what I mean.

Light mode
light-mode

Dark mode
dark-mode

I don't understand why this is changing. I have no custom styles and the component doesn't seem to change if I manually try to adjust tintColor. Is there any other way I can control this?

Apologies if this is an issue in React Navigation or in React Native itself; I just wasn't sure where to start. Thanks!

Cannot find module 'react-native-appearance'

When running a jest test on a file containing the import of the package I'm getting the following error:

'Cannot find module 'react-native-appearance'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['ts', 'js', 'json', 'node'].

After adding 'tsx' as a moduleFileExtensions:

.../react-native-appearance/src/index.tsx:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as React from 'react';

SyntaxError: Cannot use import statement outside a module

Has someone else faced the same issue?

"react-native": "0.60.5",
"jest": "24.9.0",
"ts-jest": "^24.0.2",

Not detecting Night Mode on Android

I am using react-native-appearance 0.3.2 and expo 36. Night mode system setting is not being detected on Samsung Galaxy S8 using android 9 SDK. It is working just find on iphone.

null is not an object (evaluating '_NativeAppearance.NativeAppearance.initialPreferences')

UPDATE: THE REASON IT WAS NOT WORKING IS THAT MY SDK VERSION WAS 34 AND THE PACKAGE NEEDS IT TO BE ^35. But I'm gonna leave it here anyways in case someone as dumb as me ever has the same issue.

My app is bootstrapped via expo and I am struggling to get platform theme. I installed the package using expo install react-native-appearance and put "userInterfaceStyle": "automatic" under expo > ios in app.json. But when I try to import the library I get the following error:

null is not an object (evaluating 'NativeAppearance.initialPreferences')

<unknown>
    polyfill.tsx:14:68
loadModuleImplementation
    require.js:331:6
<unknown>
    index.tsx:9:24
loadModuleImplementation
    require.js:331:6
<unknown>
    App.js:11
loadModuleImplementation
    require.js:331:6
<unknown>
   AppEntry.js:4
loadModuleImplementation
   require.js:331:6
guardedLoadModule
   require.js:197:45
global code
<unknown file>:0

I know this question has been asked before but the only suggestion was to run react-native link, which is not helping since I'm using expo (although I've tried this solution too).
These are the dependencies in my project:

"dependencies": {
    ...
    "expo": "^34.0.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz",
    "react-native-appearance": "^0.2.2",
    ...
}

Please help!

useColorScheme() not working

When using useColorScheme() as described in the description, this error message is displayed.

my package.json:

"dependencies": {
    "axios": "^0.19.0",
    "create-react-native-module": "^0.11.0",
    "expo": "^35.0.0",
     ... // more dependencies
    "react": "16.8.3",
    "react-dom": "^16.8.6",
    "react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",
    "react-native-appearance": "^0.1.0",
     ... // more dependencies
  },

Error:

Invariant Violation: Invariant Violation: Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:9396:4 in throwInvalidHookError
- node_modules/react-native-appearance/src/polyfill.tsx:78:4 in useColorScheme

Crash on AppCenter build, but not local

Somewhat new to RN, but not new to JS or iOS. So, I can run locally in sim and on device in Debug or Release xcode schemes. But when I run from an AppCenter distribution, I get this exception:

*** Terminating app due to uncaught exception 'RCTFatalException: Unhandled JS Exception: Invariant Violation: Tried to register two views with the same name RNCAppearanceProvider', reason: 'Unhandled JS Exception: Invariant Violation: Tried to register two views with the same name RNCAppearanceProvider, stack:
<unknown>@25:286
<unknown>@181:340
<unknown>@629:385
v@2:1473
<unknown>@616:740
v@2:1473
<unknown>@614:665
v@2:1473
<unknown>@423:201
v@2:1473
<unknown>@6:90
v@2:1473
d@2:875
global code@669:3
'
*** First throw call stack:
(0x1bea715f0 0x1be793bcc 0x102288870 0x10230188c 0x102302298 0x1bea77760 0x1be948b40 0x1be949718 0x1022b7404 0x1022b94f0 0x1022b9254 0x1be7369a8 0x1be737524 0x1be714b3c 0x1be71554c 0x1be71e84c 0x1be788b74 0x1be78b740)

I haven't the foggiest idea where to begin...

Can't resolve '@unimodules/react-native-adapter'

lib/module/web/SyntheticPlatformEmitter require @unimodules/react-native-adapter but its missing in package.json

Compiled with warnings.
./node_modules/react-native-appearance/lib/module/web/SyntheticPlatformEmitter.js
Module not found: Can't resolve '@unimodules/react-native-adapter' in '/node_modules/react-native-appearance/lib/module/web'

How can I force light mode on MIUI?

Hello,

I generate an app with expo,
installed react-native-appearance with this command
expo install react-native-appearance

I set config in my app.json like this

{ "expo": { "userInterfaceStyle": "light", "ios": { "userInterfaceStyle": "light" }, "android": { "userInterfaceStyle": "light" } } }

My App.tsx like this;

<AppearanceProvider> <App /> </AppearanceProvider>

What is wrong? I can't force to light mode on xiaomi mi note 10. How can I fix it?

UPDATE: I fixed on a phone manually with phone settings, but I need fix it global with app. I set on Xiaomi Mi Note 10 screen settings > dark mode > individual apps > MYAPP = disable

Dark theme does not work on MIUI 11

Hello,

I'm currently having a Xiaomi 9T running on MIUI 11 (Android 9) which currently offer a global dark mode.

When using this package, I always get 'no-preference' with useColorScheme().

I've recently developed an Android app in Java with a dark theme mode.
The app was able to detect MIUI 11's dark mode.

Is there any way that this package could also detect MIUI dark theme ?

null is not an object

I have create a project using expo init and then ejected from it. I installed this package using yarn add react-native-appearance and run react-native link react-native-appearance.

I tried importing import { Appearance } from "react-native-appearance";
But when I run the ios app yarn ios it says:

null is not an object (evaluating 'NativeAppearance.initialPreferences')

<unknown>
    polyfill.tsx:15:68
loadModuleImplementation
    require.js:331:6
<unknown>
    index.tsx:9:24
loadModuleImplementation
    require.js:331:6
<unknown>
    App.js:3
loadModuleImplementation
    require.js:331:6
<unknown>
    index.js:2
loadModuleImplementation
    require.js:331:6
guardedLoadModule
    require.js:197:45
global code
    <unknown file>:0

Simulator

OS - ios 13.1
Simulator - iPhone X

Dependencies installed

    "expo": "^35.0.0",
    "react": "16.8.3",
    "react-dom": "16.8.3",
    "react-native": "0.59.10",
    "react-native-appearance": "^0.1.0",
    "react-native-gesture-handler": "~1.3.0",
    "react-native-reanimated": "~1.2.0",
    "react-native-screens": "1.0.0-alpha.23",
    "react-native-unimodules": "~0.5.4",
    "react-native-web": "^0.11.7"

Feat: Get if system supports dark color scheme

Dark mode is a feature present only on the latest versions of android and ios (aka. android 10 and ios 13).

Currently the library returns 'no-preference' when used in older versions but it would be great if we could detect if the system supports the dark color scheme or not. It would be especially helpful in a scenario where I want to offer a dark mode for my app with a manual toggle or an option to automatically toggle based on the system (and thsi option shouldn't appear when the system doesn't support it).

I would be glad to help implement it.

Error: Cannot find module 'react-native' when used with next.js + react-native-web

Hey 👋

Trying to use this package with a next.js app with react-native-web installed, like here.

When I run the server, I encounter the following error:

ERROR

Error: Cannot find module 'react-native'
Require stack:
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/react-native-appearance/lib/commonjs/index.js
- /Users/harrisrobin/code/zaboca/www.cash/.next/server/static/development/pages/_app.js
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/next-server/server/load-components.js
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/next-server/server/api-utils.js
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/next-server/server/next-server.js
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/server/next.js
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/server/lib/start-server.js
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/cli/next-dev.js
- /Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/bin/next
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
    at Function.Module._load (internal/modules/cjs/loader.js:840:27)
    at Module.require (internal/modules/cjs/loader.js:1019:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (/Users/harrisrobin/code/zaboca/www.cash/node_modules/react-native-appearance/lib/commonjs/index.js:1:728)
    at Module._compile (internal/modules/cjs/loader.js:1133:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
    at Module.load (internal/modules/cjs/loader.js:977:32)
    at Function.Module._load (internal/modules/cjs/loader.js:877:14)
    at Module.require (internal/modules/cjs/loader.js:1019:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.react-native-appearance (/Users/harrisrobin/code/zaboca/www.cash/.next/server/static/development/pages/_app.js:659:18)
    at __webpack_require__ (/Users/harrisrobin/code/zaboca/www.cash/.next/server/static/development/pages/_app.js:23:31)
    at Module../src/pages/_app.js (/Users/harrisrobin/code/zaboca/www.cash/.next/server/static/development/pages/_app.js:113:81)
    at __webpack_require__ (/Users/harrisrobin/code/zaboca/www.cash/.next/server/static/development/pages/_app.js:23:31)
    at Object.0 (/Users/harrisrobin/code/zaboca/www.cash/.next/server/static/development/pages/_app.js:592:18) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/react-native-appearance/lib/commonjs/index.js',
    '/Users/harrisrobin/code/zaboca/www.cash/.next/server/static/development/pages/_app.js',
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/next-server/server/load-components.js',
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/next-server/server/api-utils.js',
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/next-server/server/next-server.js',
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/server/next.js',
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/server/lib/start-server.js',
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/cli/next-dev.js',
    '/Users/harrisrobin/code/zaboca/www.cash/node_modules/next/dist/bin/next'
  ]
}
[ event ] build page: /next/dist/pages/_error

Was hoping I could use this on the web in next.js. Am I missing anything?

Thank you in advance 😄

Steps to reproduce:

1 -

yarn create next-app --example with-react-native-web with-react-native-web-app

2 -
yarn add react-native-appearance

3 -
Add AppearanceProvider in _app.jsx (create this file)

_app.jsx

import * as React from "react"
import { AppearanceProvider, useColorScheme } from "react-native-appearance"
import { globalStyles } from "../styles/styles"
import { theme } from "../styles/theme"

function App({ Component, pageProps }) {
  const colorScheme = useColorScheme()

  const _theme = {
    isDarkMode: colorScheme === "dark",
    colorScheme,
    ...theme,
  }

  return (
        <AppearanceProvider>
            {globalStyles}
            <Component {...pageProps} />
        </AppearanceProvider>
  )
}

export default App

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.