Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all 28463 articles
Browse latest View live

react-native-webview: distinguish between window.location caused by script and user clicking the link

$
0
0

Is there a way in react-native-webview to distinguish between user-caused and script-caused navigations?

I see that onLoad[Start,End] and onNavigationStateChange events are fired in both cases. Also, if I add logging to WebViewClient.shouldOverrideUrlLoading() or WebViewClient.shouldInterceptRequest(), both fns are invoked if either window.location is changed inside a script, or if user clicks a link. So how can one distinguish these two?

Thanks!

EDIT: have to clarify, that I have no control over what scripts are loaded and what they are doing on the page.


Enable multidex for apps with over 64K methods

$
0
0

After Enabling the Multidex my app is crashed. I have searched everything in the internet and apply everything but not able to find the solution. This is a React Native Project.

Different domain for same URL deeplink not working in Android React Native

$
0
0

Hello friends I want to integrate deep link in my React Native Android application I have one email template inside that i have one button so when i houver that button at that time my link is as below

Email Template Link

but when it will navigate to browser at that time it will converted actual link as below

Actual Link

any My manifest file as below

<intent-filter ><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /><action android:name="android.intent.action.DOWNLOAD_COMPLETE"/></intent-filter><intent-filter android:autoVerify="true"><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:host="cpcommunityqa.azurewebsites.net" android:scheme="https" android:pathPrefix="/Event/Details"/></intent-filter>

When i try to open it from gmail it will directly open in browser not opening in application so any idea how can i solve this ? Your all suggestions are welcome

React Navigation Glitching

$
0
0

I'm experiencing strange glitching behaviour with react-navigation. See below:

View of it not working

Adjusting the height of this <View> to anything over 93px will display it correctly. For anything less, it will briefly appear for 1s and then disappear.

Here's an example of it working correctly with height: 94.

View of it working

For production we use version 2.x, I have also tested this with a more recent version (4.3.9) and got the same results.

"react-navigation": "^2.17.0""react-native": "0.59.9","react": "16.8.3",

Our stack navigator has the following config:

screen: createStackNavigator(  {    [Routes.RadioChat]: { screen: RadioChat },    [Routes.PublicProfileChat]: { screen: PublicProfileScreen },    ....  },  {    headerMode: 'none',    cardStyle: { backgroundColor: COLOR_BASE_1 },    initialRouteName: Routes.RadioChat,    transitionConfig: () => ({      transitionSpec: {        duration: 600,        easing: Easing.out(Easing.poly(4)),        timing: Animated.timing,      },      screenInterpolator: sceneProps => {        const { layout, position, scene } = sceneProps        const { index } = scene        const width = layout.initWidth        const translateX = position.interpolate({          inputRange: [index - 1, index, index + 1],          outputRange: [width, 0, 0],        })        const opacity = position.interpolate({          inputRange: [index - 1, index - 0.99, index],          outputRange: [0, 1, 1],        })        return { opacity, transform: [{ translateX }] }      },    }),  }),path: '',},

The example shows a navigation event from Routes.RadioChat to Routes.PublicProfileChat.

PublicProfileChat overlay component is:

const PublicProfileChat = class extends Component {   render() {     return (<View style={{ width: '100%', height: '100%' }}><View style={{ backgroundColor: 'red', height: 90, width: '100%' }}><Text>Sample Header</Text></View></View>    )  }}

How do I Build app with :app:bundleReleaseJsAndAssets error?

$
0
0

I need help , I need fix this error when building apk using gradlew assembleRelease , configuration is succesful , but when executing at 70% there throws an error :

> Task :app:bundleReleaseJsAndAssets_SentryUpload FAILEDerror: An organization slug is required (provide with --org)Add --log-level=[info|debug] or export SENTRY_LOG_LEVEL=[info|debug] to see more output.Please attach the full debug log to all bug reports.FAILURE: Build completed with 2 failures.1: Task failed with an exception.-----------* What went wrong:Execution failed for task ':app:bundleReleaseJsAndAssets'.> Process 'command 'cmd'' finished with non-zero exit value 1* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.==============================================================================2: Task failed with an exception.-----------* What went wrong:Execution failed for task ':app:bundleReleaseJsAndAssets_SentryUpload'.> Process 'command 'cmd'' finished with non-zero exit value 1* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

For info I tried building without bundleReleasejsAssets, but when i install app on my phone , App won"t start it"s instantly crashing , just can"t open , I think this bundleReleaseJsAssets needs to be added , or my app wont run ...

Can't find variable: regeneratorRuntime (ReactNative)

$
0
0

While trying to run my project on an android emulator, the device throws this error emulator screenshot. I cannot seem to figure out what I am doing wrong. I am still quite new to react

How to fix Undefined is not an object error when using a trylocalSingnin function

$
0
0

In my app I have multiple screens that you get access to after you seccufuly login or sign up.Am getting an undefined is not an object error when using tryLocalSignin() which is a function I used to make sure that the user doesn't enter his login info each time by checking if they are stored in asyncstorage.how do I fix this problem and make navigation work properly

Here is the code used on the App.js file :

import React, { useEffect, useContext } from "react";import "react-native-gesture-handler";import { NavigationContainer } from "@react-navigation/native";import { createMaterialBottomTabNavigator } from "@react-navigation/material-bottom-tabs";import AccountScreen from "./app/screens/AccountScreen";import SearchScreen from "./app/screens/SearchScreen";import SaveScreen from "./app/screens/SaveScreen";import { SimpleLineIcons } from "@expo/vector-icons";import { Feather } from "@expo/vector-icons";import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";import colors from "./app/config/colors";import { createStackNavigator } from "@react-navigation/stack";import { createSharedElementStackNavigator } from "react-navigation-shared-element";import MainScreen from "./app/screens/MainScreen";import DetailScreen from "./app/screens/DetailScreen";import Signin from "./app/screens/login/SigninScreen";import Signup from "./app/screens/login/SignupScreen";import { Provider as AuthProvider } from "./app/context/AuthContext";import { Context as AuthContext } from "./app/context/AuthContext";import { setNavigator } from "./app/navigationRef";const Tab = createMaterialBottomTabNavigator();const Stack = createSharedElementStackNavigator();const WelcomeStack = createStackNavigator();const MainStack = createStackNavigator();function Welcome() {  return (<WelcomeStack.Navigator><WelcomeStack.screen name="SignIn" component={Signin} /><WelcomeStack.screen name="SignUp" component={Signup} /></WelcomeStack.Navigator>  );}function MainTabScreen() {  return (<Stack.Navigator      initialRouteName="MainScreen"      screenOptions={{ headerShown: false }}><Stack.Screen name="MainScreen" component={MainScreen} /><Stack.Screen        name="DetailScreen"        component={DetailScreen}        options={(navigation) => ({          headerBackTitleVisible: false,          cardStyleInterpolator: ({ current: { progress } }) => {            return {              cardStyle: {                opacity: progress,              },            };          },        })}        sharedElements={(route) => {          const { data } = route.params;          return [            {              id: `item.${data.id}.photo`,              animation: "move",              resize: "clip",              align: "center-top",            },            {              id: `item.${data.id}.text`,              animation: "fade",              resize: "clip",              align: "left-center",            },            {              id: `item.${data.id}.profilePic`,              animation: "move",              resize: "clip",              align: "left-center",            },            {              id: `item.${data.id}.username`,              animation: "fade",              resize: "clip",              align: "left-center",            },            {              id: `item.${data.id}.readtime`,              animation: "fade",              resize: "clip",              align: "left-center",            },          ];        }}      /></Stack.Navigator>  );}function TabNav() {  return (<Tab.Navigator      initialRouteName="MainTabScreen"      activeColor={colors.shade1}      style={{ backgroundColor: "tomato" }}><Tab.Screen        name="Home"        component={MainTabScreen}        options={{          tabBarColor: "#292B34",          tabBarIcon: ({ color }) => (<SimpleLineIcons name="home" size={24} color={colors.shade2} />          ),        }}      /><Tab.Screen        name="SearchScreen"        component={SearchScreen}        options={{          tabBarLabel: "Search",          tabBarColor: "#292B34",          tabBarIcon: ({ color }) => (<Feather name="search" size={24} color={colors.shade2} />          ),        }}      /><Tab.Screen        name="SaveScreen"        component={SaveScreen}        options={{          tabBarLabel: "Save",          tabBarColor: "#292B34",          tabBarIcon: ({ color }) => (<MaterialCommunityIcons              name="bookmark"              size={24}              color={colors.shade2}            />          ),        }}      /><Tab.Screen        name="AccountScreen"        component={AccountScreen}        options={{          tabBarLabel: "Account",          tabBarColor: "#292B34",          tabBarIcon: ({ color }) => (<MaterialCommunityIcons              name="account"              size={24}              color={colors.shade2}            />          ),        }}      /></Tab.Navigator>  );}function App() {  const { tryLocalSignin } = useContext(AuthContext);  const [isLoading, setIsLoading] = React.useState(false);  useEffect(() => {    setTimeout(() => {      tryLocalSignin();      setIsLoading(!isLoading);    }, 500);  }, []);  return (<AuthProvider><NavigationContainer><MainStack.Navigator          ref={(navigator) => {            setNavigator(navigator);          }}>          {isLoading ? (<MainStack.Screen name="Tab" component={TabNav} />          ) : (<MainStack.Screen name="WelcomeStack" component={Welcome} />          )}</MainStack.Navigator></NavigationContainer></AuthProvider>  );}export default App;

React Native - Animation only works after Toggle Inspect on Android

$
0
0

I'm quite new on React/React-Native environment and I'm facing some problems with Animations on Android.

I'm using a react animation to show a bottom Alert on errors and warnings.The problem is that the animation is working fine on iOS but only works on Android after I enable the "Toggle Inspector", if I don't enable it the animation doesn't work, on debugger I'm able to see that the component is on the React components structure.

I already tried workarounds as setting the Animated.Value to 0.01 and changing Animated.createAnimatedComponent to Animated.View.

The animation should occur after the state is changed and the visible property is set to TRUE, the change of the state is OK as I can see it working on the React Native Debbuger, and the slideIn/slideOut functions are being called by the useEffect hook.

I'm on version React 16.11.0 and React-Native 0.62.2

UPDATE

I removed position: absolute from my component and now I'm able to see the animation on the top of my screen, I've tried to change the value of z-index to a higher value (I don't have any z-index higher than 1 in my app) but it didn't worked as well.

Here is the main part of the code:

export const Alert = withTheme(({ theme: { primary, textGray } }) => {  const translateValue = useRef(new Animated.Value(0)).current;  const dispatch = useDispatch();  const {    visible,    data: { type, message }  } = useSelector(({ notification }) => notification);  const slideIn = useCallback(() => {    Animated.timing(translateValue, {      toValue: 1,      duration: 1000,      useNativeDriver: true    }).start();  }, [translateValue]);  const slideOut = useCallback(() => {    Animated.timing(translateValue, {      toValue: 0,      duration: 1000,      useNativeDriver: true    }).start();  }, [translateValue]);  const handleClose = () => {    dispatch(hideNotification());  };  useEffect(() => {    if (visible) {      slideIn();    } else {      slideOut();    }  }, [visible, slideIn, slideOut]);  return (<Wrapper      style={{        transform: [          {            translateY: translateValue.interpolate({              inputRange: [0, 1],              outputRange: [300, 0]            })          }        ]      }}><Content><Icon name={icons[type]} size={20} color={primary} /><Message>{message}</Message></Content><Button        onPress={handleClose}        accessible        accessibilityRole="button"        accessibilityLabel="Fechar notificação"><Icon size={20} name="x" color={textGray} /></Button></Wrapper>  );});const Wrapper = Animated.createAnimatedComponent(styled.SafeAreaView`  width: 100%;  border-top-width: 1px;  border-top-color: ${({ theme: { border } }) => border};  background: ${({ theme: { background } }) => background};  z-index: 1;  position: absolute;  flex-direction: row;  justify-content: space-between;  align-items: center;  bottom: 0;  left: 0;`);

Task :app:createReleaseExpoManifest FAILED

$
0
0

I am trying to produce apk in a project I created with create-react-native-app. But an error like xxxx occurs. I would appreciate if anyone with knowledge helps.

Task :app:createReleaseExpoManifest FAILEDError: Failed to connect to the packager server. If you did not start this build by running 'react-native run-android', you can start the packager manually by running 'react-native start' in the project directory. (Error: connect ECONNREFUSED 127.0.0.1:8081)

enter image description hereenter image description here

Unable to resolve module `./Linking/Linking` from `node_modules/expo/build/ExpoLazy.js`

$
0
0

Has anyone experience this error with expo, when running react-native run-android?

error: bundling failed: Error: Unable to resolve module `./Linking/Linking` from `node_modules/expo/build/ExpoLazy.js`: None of these files exist:  * node_modules/expo/build/Linking/Linking(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)  * node_modules/expo/build/Linking/Linking/index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)

"expo": "^37.0.9",

npx react-native run-android: E/Device: Error during Sync: EOF

$
0
0

I am trying to run react native app to my real android device.I checked my device before running

adb devicesList of devices attached3357425441473098        device

I started with

npx react-native start

and in other console

npx react-native run-android

But got an error..

Task :app:installDebug FAILED                                                                                                                                                     10:25:40 V/ddms: execute: running am get-config                                                                                                                                     10:25:40 V/ddms: execute 'am get-config' on '3357425441473098' : EOF hit. Read: -1                                                                                                  10:25:40 V/ddms: execute: returning                                                                                                                                                 Installing APK 'app-debug.apk' on 'SM-G960U - 9' for app:debug                                                                                                                      10:25:40 D/app-debug.apk: Uploading app-debug.apk onto device '3357425441473098'10:25:40 D/Device: Uploading file onto device '3357425441473098'10:25:40 D/ddms: Reading file permision of /home/user/react-native/awesomeProject/android/app/build/outputs/apk/debug/app-debug.apk as: rw-rw-r--                10:25:40 D/ddms: read: channel EOF                                                                                                                                                  10:25:40 E/Device: Error during Sync: EOF                                                                                                                                           Unable to install /home/user/react-native/awesomeProject/android/app/build/outputs/apk/debug/app-debug.apk                           com.android.ddmlib.InstallException: EOF      

And right after that error. I lost my device connection.

adb devices

shows nothing..

and at the bottom of stacktrace I see this error also

Caused by: java.io.IOException: EOF        at com.android.ddmlib.AdbHelper.read(AdbHelper.java:862)        at com.android.ddmlib.SyncService.doPushFile(SyncService.java:712)        at com.android.ddmlib.SyncService.pushFile(SyncService.java:406)        at com.android.ddmlib.Device.syncPackageToDevice(Device.java:988)        at com.android.ddmlib.Device.installPackage(Device.java:902)

FAILURE: Build failed with an exception.

* What went wrong:Execution failed for task ':app:installDebug'.> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: EOF* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.* Get more help at https://help.gradle.orgBUILD FAILED in 10s    at checkExecSyncError (child_process.js:629:11)    at execFileSync (child_process.js:647:13)    at runOnAllDevices (/home/user/react-native/newProject/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:39)    at buildAndRun (/home/user/react-native/newProject/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:158:41)    at then.result (/home/user/react-native/newProject/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:125:12)    at process._tickCallback (internal/process/next_tick.js:68:7)

My device is us samsumg galaxy s9. It was working when I use Expo sdk. What is my problem?

react-native : 0.61.5

Weird thing is that it works first execution after computer boot. then I tried reconnect phone, and it pops up again.

Java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp

$
0
0

Screenshot from Android Studio

Google Play Services

This is React Native project. I have an error after successful build in Android Studio Emulator:

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp

My files:

package.json:

..."react-native": "^0.55.3","react-native-camera": "1.1.2","react-native-check-box": "^2.1.0","react-native-extended-stylesheet": "^0.8.1","react-native-firebase": "^4.2.0","react-native-geocoder": "^0.5.0","react-native-git-upgrade": "^0.2.7","react-native-htmlview": "^0.12.1","react-native-image-picker": "^0.26.10","react-native-linear-gradient": "^2.4.0","react-native-local-storage": "^1.5.2","react-native-maps": "^0.21.0","react-native-modal": "^5.4.0","react-native-modal-dropdown": "^0.6.1","react-native-read-more-text": "^1.0.0","react-native-router-flux": "^4.0.0-beta.27","react-native-svg-image": "^2.0.1","react-native-text-input-mask": "^0.7.0",...

android/app/build.gradle:

...    android {    compileSdkVersion 27    buildToolsVersion "27.0.1"    defaultConfig {        applicationId "com.something.anything"        minSdkVersion 16        targetSdkVersion 22        versionCode 1        versionName "1.0"        ndk {            abiFilters "armeabi-v7a", "x86"        }        multiDexEnabled true    }    signingConfigs {        release {            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {                storeFile file(MYAPP_RELEASE_STORE_FILE)                storePassword MYAPP_RELEASE_STORE_PASSWORD                keyAlias MYAPP_RELEASE_KEY_ALIAS                keyPassword MYAPP_RELEASE_KEY_PASSWORD            }        }    }    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86"        }    }    buildTypes {        release {            signingConfig signingConfigs.release            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }    }    // applicationVariants are e.g. debug, release    applicationVariants.all { variant ->        variant.outputs.each { output ->            // For each separate APK per architecture, set a unique version code as described here:            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits            def versionCodes = ["armeabi-v7a":1, "x86":2]            def abi = output.getFilter(OutputFile.ABI)            if (abi != null) {  // null for the universal-debug, universal-release variants                output.versionCodeOverride =                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode            }        }    }}dependencies {    compile(project(':react-native-firebase')) {        transitive = false    }    compile project(':react-native-geocoder')    compile(project(':react-native-maps')) {      exclude group: 'com.google.android.gms', module: 'play-services-base'      exclude group: 'com.google.android.gms', module: 'play-services-maps'      exclude group: 'com.google.android.gms', module: 'play-services-location'    }    compile 'com.google.android.gms:play-services-base:15.+'    compile 'com.google.android.gms:play-services-maps:15.+'    compile 'com.google.android.gms:play-services-location:15.+'    compile (project(':react-native-camera')) {    exclude group: "com.google.android.gms"    compile 'com.android.support:exifinterface:25.+'    compile ('com.google.android.gms:play-services-vision:12.0.1') {        force = true        }    }    compile project(':react-native-text-input-mask')    compile project(':react-native-linear-gradient')    compile project(':react-native-image-picker')    compile fileTree(dir: "libs", include: ["*.jar"])    compile "com.android.support:appcompat-v7:23.0.1"    compile "com.facebook.react:react-native:+"  // From node_modules}allprojects {    repositories {        maven { url "https://jitpack.io" }        maven { url "https://maven.google.com" }    }}// Run this once to be able to run the application with BUCK// puts all compile dependencies into folder libs for BUCK to usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    repositories {        jcenter()        google()    }    dependencies {        classpath 'com.android.tools.build:gradle:3.1.0'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        mavenLocal()        jcenter()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url "$rootDir/../node_modules/react-native/android"        }    }}subprojects {  project.configurations.all {     resolutionStrategy.eachDependency { details ->        if (details.requested.group == 'com.android.support'&& !details.requested.name.contains('multidex')        ) {           details.useVersion "27.1.0"        }     }  }}

I've tried a lot of solutions but nothing helped.

Apk crashes when Release mode but in debug mode works perfectly

$
0
0

I have get apk with release mode, but app crash.but apk with debug apk is not crashthis is my android/app/build.gradle

signingConfigs {    debug {        storeFile file('debug.keystore')        storePassword 'android'        keyAlias 'androiddebugkey'        keyPassword 'android'    } }    buildTypes {    debug {        signingConfig signingConfigs.debug    }    release {        // Caution! In production, you need to generate your own keystore file.        // see https://facebook.github.io/react-native/docs/signed-apk-android.        signingConfig signingConfigs.debug        minifyEnabled enableProguardInReleaseBuilds        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"    } }

How to develop Chat functionality in react native app

$
0
0

Want to develop real time Chat/Messaging functionality in react native app. in which user can send videos,pictures,voice messages and emojis.

as well as require functionality to delete messages and manage message time stamps.

What are the best methods/ways/framework to achive this?

I did npx react-native run-android but doesn't works

$
0
0

I did that command to start the react-native application, but it returns that failure.

"Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.Use '--warning-mode all' to show the individual deprecation warnings.See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

  • Where:Build file 'C:\Users\Usuario\Desktop\soorteiooo\node_modules\react-native-reanimated\android\build.gradle' line: 89

  • What went wrong-A problem occurred configuring project ':react-native-reanimated'.

    SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\Usuario\Desktop\soorteiooo\android\local.properties'.

  • Try-Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 7s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

  • Where:Build file 'C:\Users\Usuario\Desktop\soorteiooo\node_modules\react-native-reanimated\android\build.gradle' line: 89

  • What went wrong-A problem occurred configuring project ':react-native-reanimated'.

    SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\Usuario\Desktop\soorteiooo\android\local.properties'.

  • Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 7s

at makeError (C:\Users\Usuario\Desktop\soorteiooo\node_modules\execa\index.js:174:9)at Promise.all.then.arr (C:\Users\Usuario\Desktop\soorteiooo\node_modules\execa\index.js:278:16)at process._tickCallback (internal/process/next_tick.js:68:7)"

react-native statusBar with expo on iOS

$
0
0

I was trying to change the color of the statusBar on my react-native app.

I am working with expo and on their documentation they are just specifying to add :"androidStatusBar": {"backgroundColor": "#2E1D59" }

that works fine with android, but they did not mention how to do so with iOS statusBar.

Anyone has an idea about this ?

React native TouchableOpacity onPress not working on Android

$
0
0

TouchabelOpacity works fine on iOS but the onPress method does not work on Android for me.

My react-native version: 0.57.4

My code:

const initDrawer = navigation => (<TouchableOpacity    style={{ left: 16 }}    onPress={() => onPressDrawerButton(navigation)}><Ionicons name="ios-menu" color="white" size={30} /></TouchableOpacity>);

Changing app navigation structure from version 4 to 5 in react native

$
0
0

I was working on an old app using react navigation version 4 the app contains a register and login in page obviously and then the content of the app.

recently I started remaking the content of the app using react navigation version 5 in order to use the shared element animation and the bottom tab navigator and it was fairly simple.

but I struggled with converting the login part to version 5 since the app structure is somewhat complicated and I am somewhat new to react navigation version 5.

i will leave a figure of the app structure bellow a long with samples of the code used.

Navigation used in the app

App.js :

import { setNavigator } from "./app/navigationRef";const articleListFlow = createStackNavigator({  Main: MainScreen, // screen with diffrent articles categories  ResultsShow: ResultShowScreen, // article details screen});const loginFlow = createStackNavigator({  Signup: SignupScreen,  Signin: SigninScreen,});loginFlow.navigationOptions = () => {  return {    headerShown: false,  };};articleListFlow.navigationOptions = {  title: "News Feed",  tabBarIcon: ({ tintColor }) => (<View><Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} /></View>  ),  activeColor: "#ffffff",  inactiveColor: "#ebaabd",  barStyle: { backgroundColor: "#d13560" },};const switchNavigator = createSwitchNavigator({  ResolveAuth: ResolveAuthScreen,  MainloginFlow: createSwitchNavigator({    //WelcomeScreen: WeclomeScreen,    loginFlow: loginFlow,  }),  mainFlow: createMaterialBottomTabNavigator(    {      articleListFlow: articleListFlow,      ArticleSave: ArticleSaveScreen, // we dont need this one      Account: AccountScreen,    },    {      activeColor: "#ffffff",      inactiveColor: "#bda1f7",      barStyle: { backgroundColor: "#6948f4" },    }  ),});const App = createAppContainer(switchNavigator);export default () => {  return (<AuthProvider><App        ref={(navigator) => {          setNavigator(navigator);        }}      /></AuthProvider>  );};

NavigationRef.js :

import { NavigationActions } from "react-navigation";let navigator;export const setNavigator = (nav) => {  navigator = nav;};export const navigate = (routeName, params) => {  navigator.dispatch(    NavigationActions.navigate({      routeName,      params,    })  );};// routename is the name of the routes singin singup accountscreen// params information we want to pass to the screen we want to show

AuthContext.js

import { AsyncStorage } from "react-native";import createDataContext from "./createDataContext";import userAPI from "../api/user";// using navigate to access the navigator and redirect the userimport { navigate } from "../navigationRef";// AUTHENTICATION REDUCERSconst authReducer = (state, action) => {  switch (action.type) {    case "add_error": {      return {        ...state,        errorMessage: action.payload,      };    }    case "clear_error_message": {      return {        ...state,        errorMessage: "",      };    }    case "signin": {      return {        errorMessage: "",        token: action.payload,      };    }    default:      return state;  }};// CLEARING ERROR MESSAGES WHEN SWITCHING SIGNIN-SIGNUPconst clearErrorMessage = (dispatch) => () => {  dispatch({ type: "clear_error_message" });};// AUTOMATIC SIGNIN ONLY USING TOKENS ON USER DEVICEconst tryLocalSignin = (dispatch) => async () => {  const token = await AsyncStorage.getItem("token");  if (token) {    // if token exists    dispatch({ type: "signin", payload: token });    navigate("Main");  } else {    // if token doesnt exist    navigate("WelcomeScreen");  }};// SIGNUPconst signup = (dispatch) => async ({ email, password }) => {  try {    const response = await userAPI.post("/signup", { email, password });    await AsyncStorage.setItem("token", response.data.token);    dispatch({ type: "signin", payload: response.data.token });    // making use of the navigate component to access navigation    // and redirect the user    navigate("Main");  } catch (err) {    dispatch({      type: "add_error",      payload: "Something went wrong with sign up",    });  }};// SIGNINconst signin = (dispatch) => async ({ email, password }) => {  try {    const response = await userAPI.post("/signin", { email, password });    await AsyncStorage.setItem("token", response.data.token);    // using signin since the logic is the same    dispatch({ type: "signin", payload: response.data.token });    // making use of the navigate component to access navigation    // and redirect the user    navigate("Main");  } catch (err) {    console.log(err);    dispatch({      type: "add_error",      payload: "Something went wrong with sign in",    });  }};// SIGNOUTconst signout = (dispatch) => async () => {  // removing the token makes identification not work again  await AsyncStorage.removeItem("token");  dispatch({ type: "signout" });  navigate("loginFlow");};// CREATING CONTEXT AND PROVIDER OBJECTS FOR AUTHENTICATIONexport const { Provider, Context } = createDataContext(  authReducer,  {    signin,    signup,    signout,    clearErrorMessage,    tryLocalSignin,  },  {    token: null,    errorMessage: "",  });

createDataContext.js

import React, { useReducer } from "react";export default (reducer, actions, defaultValue) => {  const Context = React.createContext();  const Provider = ({ children }) => {    const [state, dispatch] = useReducer(reducer, defaultValue);    const boundActions = {};    for (let action in actions) {      // for every action in the actions, call it with dispatch      boundActions[action] = actions[action](dispatch);    }    return (<Context.Provider value={{ state, ...boundActions }}>        {children}</Context.Provider>    );  };  return { Context, Provider };};

My appologies for the long code and thank you in advance for anyone who can help.

React Native, Android Log.

$
0
0

Is there a way in react native to see the log from native (java) modules of android?

I'm using javas log module https://developer.android.com/reference/android/util/Log.html - but I'm not getting anything from there. and to be honest I'm not sure how to use it if it's at all possible. atm there isn't much code - it's just

    Log.d("Notification","Notify App");

Because I want to see if I can see the notifications somewhere - I do know the java module is registered correctly as I'm calling other functions from it.

Thanks!

React Native blank screen on android emulator

$
0
0

I am new to React Native and Redux, currently am working on delivery app for android. Problem is that everytime i run code on android emulator the blank screen is showing:https://i.stack.imgur.com/A0lk2.png. I tried on my phone also same problem, but debugger is not showing any errors. Here is my code:

App.js

import React, { Component } from 'react';import { PersistGate } from 'redux-persist/integration/react';import { persistStore } from 'redux-persist';import HomeScreen from "./src/screens/HomeScreen";import LoginScreen from "./src/screens/LoginScreen";import RegistrationScreen from "./src/screens/RegistrationScreen";import { Provider } from './src/context/AuthContext';import LoadingScreen from './src/screens/LoadingScreen';import store from './store';import { connect } from 'react-redux';import { NavigationContainer } from '@react-navigation/native';import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'const BottomTabNavigator = createBottomTabNavigator();class Appliaction extends Component {  componentWillMount() {    this.props.getLocalization(this.props.token);  }  render() {    return (      BottomNavigation = () => {<NavigationContainer style={{ flex: 1 }}><BottomTapBarNavigator.Navigator><BottomTabNavigator.Screen name='Register' component={RegistrationScreen} options={{ title: "" }} /><BottomTabNavigator.Screen name='Login' component={LoginScreen} options={{ title: "" }} /><BottomTabNavigator.Screen name='Home' component={HomeScreen} options={{ title: "" }} /></BottomTapBarNavigator.Navigator></NavigationContainer >      }    )  }}const mapStateToProps = (state) => {  return {    localizationNew: state.localizationReducer.localizationNew,    token: state.ClientReducer.token,    loading: state.generalReducer.loading,  };};const mapDispacthToProps = (dispacth) => {  return {    getLocalization: token => dispacth(getLocalization(token))  }}const ConnectedApp = connect(mapStateToProps, mapDispacthToProps)(Appliaction);const persistor = persistStore(store);const App = () => {  return (<Provider store={store} ><PersistGate loading={null} persistor={persistor}><ConnectedApp /></PersistGate ></Provider >  );};export default App;

Store.js

import { applyMiddleware, createStore, combineReducers } from 'redux';import { createLogger } from 'redux-logger';import thunkMiddleware from 'redux-thunk';import ClientReducer from './src/reducers/ClientReducer';const middleware = applyMiddleware(thunkMiddleware, createLogger());export default createStore(ClientReducer, middleware);

ClientReducer.js

import { Alert } from 'react-native';import { navigator } from '../navigatorRef';import { CLIENT } from '../constants/ActionTypeConstants';import { StackActions } from 'react-navigation';const initalState = {    username: '',    email: '',    token: '',    signupSuccessful: false};const ClientReducer = (state = initalState, action) => {    switch (action.type) {        case CLIENT.LOGIN: {            return { ...state, token: action.token };        }        case CLIENT.REGISTER: {            return { ...state, signupSuccessful: true }        }        case CLIENT.RESET_REGISTER: {            return { ...state, signupSuccessful: false }        }        case CLIENT.LOGOUT: {            const resetAction = StackActions.reset({                index: 0,                actions: [navigator.navigate({ routeName: 'Home' })],            });            navigator.dispatch(resetAction);            return { ...state, token: '' };        }        case CLIENT.REMOVE_TOKEN: {            if (action.status === 401) {                Alert.alert('Your session has expired');                const resetAction = StackActions.reset({                    index: 0,                    actions: [navigator.navigate({ routeName: 'Home' })],                });                navigator.dispatch(resetAction);            }            return { ...state, token: '' };        }        default: {            return state;        }    }};export default ClientReducer;

LoginScreen.js

import React, { Component } from 'react';import { StyleSheet, View } from 'react-native';import { connect } from 'react-redux';import { StackActions, NavigationActions } from 'react-navigation';import { LoginButton } from '../components/LoginButton';import { login } from '../actions/ClientAction';import { registerButtonOpen, registerButtonClosed } from "../actions/ActionTypes";import { strings } from '../components/string';const styles = StyleSheet.create({  container: {    flex: 1  },  contentContainerStyle: {    alignContent: 'center',    alignItems: 'center',    justifyContent: 'center'  }});class LoginScreen extends Component {  constructor(props) {    super(props);    this.state = {      email: '',      password: '',      disabled: false    };    this.handleEmailChange = this.handleEmailChange.bind(this);    this.handlePasswordChange = this.handlePasswordChange.bind(this);    this.loginButtonPress = this.loginButtonPress.bind(this);  }  handleEmailChange = (event) => {    this.setState({ email: event });  };  handlePasswordChange = (event) => {    this.setState({ password: event });  };  loginButtonPress = async () => {    await this.setState({ disabled: true });    this.props.registerButtonOpen();    await this.props.login({      email: this.state.email,      password: this.state.password    });    if (this.props.token) {      const resetAction = StackActions.reset({        index: 0,        actions: [NavigationActions.navigate({ routeName: "Main" })]      });      await this.props.getAllCars(this.props.token);      navigationService.dispacth(resetAction);    }    this.props.registerButtonClosed();  };  render() {    const isEnabled = this.state.email.length > 0 && this.state.password.length > 0;    return (<View style={styles.container}><Input          placeholder={strings.login.email}          value={this.state.email}          onChangeText={this.handleEmailChange}        /><Input          placeholder={strings.login.password}          value={this.state.password}          onChangeText={this.handlePasswordChange}        /><LoginButton onPress={this.loginButtonPress} disabled={!isEnabled || this.state.disabled} /></View>    );  }}const mapStateToProps = (state) => {  return {    token: state.clientReducer.token  };};const mapDispatchToProps = (dispacth) => {  return {    login: data => dispacth(login(data)),    registerButtonOpen: () => dispacth(registerButtonOpen()),    registerButtonClosed: () => dispacth(registerButtonClosed())  };};export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen);// import React, { useState, useContext } from "react";// import { StyleSheet, View, TouchableOpacity, AsyncStorage } from "react-native";// import { Text, Input, Button } from 'react-native-elements';// import tracker from '../../api/tracker';// import Spacer from '../components/Spacer';// import { Context as AuthContext } from '../context/AuthContext';// import { NavigationEvents } from 'react-navigation';// const LoginScreen = ({ navigation }) => {//   const { state, signin, clearErrorMessage } = useContext(AuthContext);//   const [email, setEmail] = useState('');//   const [password, setPassword] = useState('');//   return (//     <View style={styles.container}>//       <NavigationEvents//         onWillBlur={clearErrorMessage}//       />//       <Spacer />//       <Input//         label="Email/Username: "//         value={email}//         onChangeText={setEmail}//       />//       <Spacer />//       <Input//         label="Password: "//         secureTextEntry={true}//         value={password}//         onChangeText={setPassword}//       />//       {state.errorMessage ? <Text style={{ color: 'red' }}>{state.errorMessage}</Text> : null}//       <Spacer />//       <Spacer />//       <Button//         title={'Login'}//         onPress={() => signin({ email, password })}//       />//       <Spacer />//       <TouchableOpacity onPress={() => { navigation.navigate('Register') }}>//         <Spacer>//           <Text style={styles.link}>Don't have an account? Register now!</Text>//         </Spacer>//       </TouchableOpacity>//       <TouchableOpacity onPress={() => { navigation.navigate('Account') }}>//         <Spacer>//           <Text style={styles.link}>Go to Account screen!</Text>//         </Spacer>//       </TouchableOpacity>//     </View>//   )// }// LoginScreen.navigationOptions = () => {//   return {//     headerShown: false//   };// };// const styles = StyleSheet.create({//   container: {//     flex: 1,//     //alignItems: 'center',//     justifyContent: 'center',//     backgroundColor: '#ecf0f1',//     marginBottom: 100//   },//   link: {//     color: 'blue'//   }// });// export default LoginScreen;

RegistrationScreen.js

import React, { Component } from 'react';import { connect } from 'react-redux';import { StackActions } from 'react-navigation';import { NavigationEvents } from "react-navigation";import { StyleSheet, View, Alert } from 'react-native';import { Button, Input } from 'react-native-elements';import { register, resetRegister } from '../actions/ClientAction';import { registerButtonOpen, registerButtonClosed } from "../actions/ActionTypes";import { REGISTER_BUTTON } from '../constants/ActionTypeConstants'import { ClientReducer } from '../reducers/ClientReducer';class RegistrationScreen extends Component {    constructor(props) {        super(props);        this.state = {            firstName: '',            userName: '',            email: '',            address: '',            password: '',            confirmPassword: ''        };        this.handleFirstNameChange = this.handleFirstNameChange.bind(this);        this.handleUserNameChange = this.handleUsertNameChange.bind(this);        this.handleEmailNameChange = this.handleEmailNameChange.bind(this);        this.handlePasswordNameChange = this.handlePasswordNameChange.bind(this);        this.handleConfirmPasswordNameChange = this.handleConfirmPasswordNameChange.bind(this);        this.handleAdressNameChange = this.handleAdressNameChange.bind(this);        this.registerButton = this.registerButton.bind(this);        this.validateForm = this.validateForm.bind(this);    }    handleFirstNameChange = (event) => {        this.setState({ firstName: event });    };    handleUserNameChange = (event) => {        this.setState({ userName: event })    };    handleEmailNameChange = (event) => {        this.setState({ email: event })    };    handlePasswordNameChange = (event) => {        this.setState({ password: event })    };    handleConfirmPasswordNameChange = (event) => {        this.setState({ confirmPassword: event })    };    registerButton = async () => {        if (this.validateForm()) {            this.props.registerButtonOpen();            await this.props.register({                firstName: this.props.firstName,                userName: this.props.userName,                email: this.props.email,                address: this.props.address,                password: this.props.password            });            this.props.registerButtonClosed();            if (this.props.registerSuccess) {                Alert.alert(strings.register.alerts.registerSuccessful);                const resetAction = StackActions.reset({                    actions: [NavigationEvents.navigate({ routeName: 'HomeScreen' })]                });                this.props.resetRegister();                NavigationService.dispacth(resetAction);            }        }    };    validateForm = () => {        if (!this.state.firstName) {            Alert.alert(strings.alerts.firstNameMandatory);            return false;        }        if (!this.state.userName) {            Alert.alert(strings.alerts.userNameMandatory);            return false;        }        if (!this.state.email) {            Alert.alert(strings.alerts.emailMandatory);            return false;        }        if (!this.state.address) {            Alert.alert(strings.alerts.addresMandatory);            return false;        }        if (!this.state.password) {            Alert.alert(strings.alerts.passwordandatory);            return false;        }        if (this.state.password !== this.state.confirmPassword) {            Alert.alert(strings.alerts.confimPasswordMandatory);            return false;        }        return true;    }    render() {        return (<View style={styles.container}><Input                    placeholder={strings.registration.firstname}                    value={this.state.firstName}                    onChangeText={this.handleFirstNameChange}                /><Input                    placeholder={strings.registration.username}                    value={this.state.userName}                    onChangeText={this.handleUserNameChange}                /><Input                    placeholder={strings.registration.email}                    value={this.state.email}                    onChangeText={this.handleEmailNameChange}                /><Input                    placeholder={strings.registration.adress}                    value={this.state.address}                    onChangeText={this.handleAdressNameChange}                /><Input                    placeholder={strings.registration.password}                    value={this.state.password}                    onChangeText={this.handlePasswordNameChange}                /><Input                    placeholder={strings.registration.confirm}                    value={this.state.confirmPassword}                    onChangeText={this.handleConfirmPasswordNameChange}                /><registerButton onPress={this.registerButton} /></View>        );    }}const mapStateToProps = (state) => {    return {        registerSuccessful: state.ClientReducer.registerSuccessful    };};const mapDispatchToProps = (dispacth) => {    return {        register: data => dispacth(register(data)),        resetRegister: () => dispacth(resetRegister()),        registerButtonOpen: () => dispacth(registerButtonOpen()),        registerButtonClosed: () => dispacth(registerButtonClosed())    };};const styles = StyleSheet.create({    container: {        flex: 1    },    contentContainerStyle: {        alignContent: 'center',        alignItems: 'center',        justifyContent: 'center'    }});export default connect(mapStateToProps, mapDispatchToProps)(RegistrationScreen);// import React, { useState, useContext } from "react";// import { StyleSheet, View, TouchableOpacity } from "react-native";// import { Text, Input, Button } from 'react-native-elements';// import tracker from '../../api/tracker';// import Spacer from '../components/Spacer';// import { Context as AuthContext } from '../context/AuthContext';// import { NavigationEvents } from "react-navigation";// const RegistrationScreen = ({ navigation }) => {//     const { state, signup, clearErrorMessage } = useContext(AuthContext);//     const [firstName, setFirstName] = useState('');//     const [userName, setUserName] = useState('');//     const [password, setPassword] = useState('');//     const [email, setEmail] = useState('');//     const [address, setAddress] = useState('');//     return (//         <View style={styles.container}>//             <NavigationEvents//                 onWillBlur={clearErrorMessage}//             />//             <Text h4>Fill the form</Text>//             <Spacer />//             <Input//                 placeholder={'Enter full name'}//                 value={firstName}//                 onChangeText={setFirstName}//             />//             <Spacer />//             <Input//                 placeholder={'Enter username'}//                 value={userName}//                 onChangeText={setUserName}//             />//             <Spacer />//             <Input//                 placeholder={'Enter password'}//                 secureTextEntry={true}//                 value={password}//                 onChangeText={setPassword}//             />//             <Spacer />//             <Input//                 placeholder={'Enter email'}//                 value={email}//                 onChangeText={setEmail}//             />//             <Spacer />//             <Input//                 placeholder={'Enter address'}//                 value={address}//                 onChangeText={setAddress}//             />//             {state.errorMessage ? <Text style={{ color: 'red' }}>{state.errorMessage}</Text> : null}//             <Spacer />//             <Spacer />//             <Button//                 title={'Register'}//                 onPress={() => signup({ firstName, userName, password, email, address })}//             />//             <Spacer />//             <TouchableOpacity onPress={() => navigation.navigate('Login')}>//                 <Spacer>//                     <Text style={styles.link}>Already have an account? Login now!</Text>//                 </Spacer>//             </TouchableOpacity>//             <Spacer />//         </View>//     )// }// RegistrationScreen.navigationOptions = () => {//     return {//         headerShown: false//     };// };// const styles = StyleSheet.create({//     container: {//         flex: 1,//         alignItems: 'center',//         justifyContent: 'center',//         backgroundColor: '#ecf0f1',//     },//     link: {//         color: 'blue'//     }// });// export default RegistrationScreen;

Thanks in advance :) .

Viewing all 28463 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>