Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow

tsconfig.json shows error: Entry point for implicit type library 'glob'

$
0
0

I have a Monorepo which uses Typescript. I have a common folder which shows this error on the top of the file -> Entry point for implicit type library 'glob'. I am not sure what is wrong with the configuration.

Screenshot:

enter image description here

tsconfig.json

{"extends": "../../tsconfig.json","compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"isolatedModules": true,"jsx": "react-native","lib": ["es2021"    ],"moduleResolution": "node","noEmit": false,"strict": true,"target": "esnext","composite": true,"rootDir": ".","outDir": "dist","declaration": true,"emitDeclarationOnly": true,"declarationMap": true},"exclude": ["node_modules",]}

Any Suggestions?


How to make local shared TypeScript package available during EAS Build for Expo/React Native project?

$
0
0

EAS Build Cannot Resolve Local Shared TypeScript Package in Monorepo

Project Structure

I have a monorepo setup with a shared TypeScript package that works perfectly in development but fails during EAS Build.

Folder Structure.

my-app/
├── mobile-app/ # Expo React Native app
│├── package.json # Contains "@shared/types": "file:./shared_local"
│├── eas.json
│├── shared_local/ # Local copy for EAS build
││├── package.json
││├── dist/ # Built files
││└── src/
│└── src/ # App imports from "@shared/types"
├── shared/ # Original shared package
│├── package.json # Name: "@shared/types"
│└── src/ # TypeScript interfaces & types
└── cloud-functions/ # Also uses shared types

Problem

The @myProjectName/shared package works locally but EAS Build fails with:
Error: Unable to resolve module @myProjectName/shared from /home/expo/workingdir/build/src/app/(tabs)/adminTab/data-seeder/stores.tsx: @myProjectName/shared could not be found within the project or in these directories:node_modules23 | StoreType,24 | User,

25 | } from "@myProjectName/shared";

How can I make a local TypeScript package available during EAS Build?

React Native Reanimated: useScrollViewOffset not working with stickyHeaderIndices and absolutely positioned views

$
0
0

I'm trying to create an animated header that moves based on scroll position using React Native Reanimated, but the useScrollViewOffset hook isn't tracking scroll events properly when combined with stickyHeaderIndices and absolutely positioned views.

What I'm trying to achieve:

A yellow header that animates based on scroll positionThe header should move up as the user scrolls downUsing useScrollViewOffset to get scroll values

The Problem:The console.log in useDerivedValue shows that the scroll offset is not updating, staying at 0 even when scrolling through the content.

import {useWindowDimensions} from 'react-native';import React from 'react';import Animated, {  useAnimatedRef,  useAnimatedStyle,  useDerivedValue,  useScrollViewOffset,  withSpring,} from 'react-native-reanimated';const Topbar = () => {  const {width, height} = useWindowDimensions();  const testData: string[] = ['red', 'blue', 'orange'];  const scrollViewRef = useAnimatedRef<Animated.ScrollView>();  const scrollViewOffset = useScrollViewOffset(scrollViewRef);  const translateY = useDerivedValue(() => {    console.log(Math.min(Math.max(scrollViewOffset.value, 0), height * 0.05));    return Math.min(Math.max(scrollViewOffset.value, 0), height * 0.05);  });  const animatedStyles = useAnimatedStyle(() => ({    transform: [{translateY: withSpring(-translateY.value)}],  }));  return (<Animated.ScrollView      style={{        width: width,        backgroundColor: 'orange',        flexDirection: 'column',      }}      stickyHeaderIndices={[0]}      ref={scrollViewRef}><Animated.View        style={[          {            width: width,            height: height * 0.5,            backgroundColor: 'yellow',            position: 'absolute',            top: 0,            zIndex: 1,          },          animatedStyles,        ]}      />      {testData.map(color => {        return (<Animated.View            style={{              width,              height: height,              backgroundColor: color,            }}            key={color}          />        );      })}</Animated.ScrollView>  );};export default Topbar;

Environment:

  • React Native: 0.79.3

  • react-native-reanimated: 3.18.0

  • Platform: iOS/Android

Any help would be greatly appreciated!

  1. Removing stickyHeaderIndices - this makes the scroll tracking work, but I lose the sticky behavior
  2. Changing the positioning from absolute to relative - scroll tracking works but layout breaks
  3. Different combinations of styles and properties

Error “Requiring unknown module ‘undefined’” with AWS SDK v3 in Expo SDK 52 (Hermes) when using @aws-sdk/client-cognito-identity-provider

$
0
0

I’m migrating my app to Expo SDK 52 (Hermes) and using AWS SDK v3 to call Cognito from React Native:

import { CognitoIdentityProviderClient } from '@aws-sdk/client-cognito-identity-provider';import { LambdaClient } from '@aws-sdk/client-lambda';import AWS from 'aws-sdk';export const cognitoClient = new CognitoIdentityProviderClient({  region: process.env.EXPO_PUBLIC_AWS_REGION,  credentials: {    accessKeyId: process.env.EXPO_PUBLIC_AWS_ACCESS_KEY_ID!,    secretAccessKey: process.env.EXPO_PUBLIC_AWS_SECRET_ACCESS_KEY!,  },});

In one of my modules I do:

export const userExists = async (  username: string,): Promise<UserCheckResponse> => {  try {    const command = new AdminGetUserCommand({      UserPoolId: process.env.EXPO_PUBLIC_AWS_USER_POOL_ID!,      Username: username,    });    const response: AdminGetUserCommandOutput =      await cognitoClient.send(command);    return {      userId: response.Username || null,      userConfirmed: response.UserStatus === 'CONFIRMED',    };  } catch (error: any) {    if (error.name === 'UserNotFoundException') {      return {        userId: null,        userConfirmed: null,      };    } else {      throw new Error('Failed to check user existence.');    }  }};

When I run the app on a device (or emulator) with Hermes, calling userExists() immediately throws:

ERROR  Error: Requiring unknown module "undefined". If you are sure the module exists, try restarting Metro. You may also want to run `yarn`or`npm install`. … [Component Stack]

I also see this warning from Expo Router:

WARN  Route "./Auth/index.tsx" is missing the required default export. Ensure a React component is exported as default. [Component Stack]

What I’ve tried:

  • Restarting Metro with expo start -c
  • Deleting node_modules+package-lock.json+npm cache clean --force+npm install
  • Adding recommended polyfills at the top of my App.tsx:
import 'react-native-get-random-values';import 'react-native-url-polyfill/auto';import { ReadableStream } from 'web-streams-polyfill';globalThis.ReadableStream = ReadableStream;
  • Ensuring cognitoClient is initialized before any commands run
  • Verifying that my Auth/index.tsx component indeed has a export default function Auth() { … }

None of these eliminated the Requiring unknown module ‘undefined’ error.

My questions:

  • What is causing the Requiring unknown module "undefined" error when using @aws-sdk/client-cognito-identity-provider under Hermes in Expo SDK 52?
  • Are there any additional polyfills or special configuration needed for AWS SDK v3 to work in Expo/Hermes?
  • Is the Expo Router warning about missing default export related to this failure, or is it a separate issue?

Any guidance on integrating Cognito with Expo SDK 52 would be greatly appreciated. Thanks!

How do I un-constrain an absolutely positioned element's width so that it may grow beyond the parent

$
0
0

Why are absolutely positioned elements in React-Native still relative to the parent with their width? If I use a text with a flairText style as I've written in my example the text inside will still wrap if it would exceed the height of the parent it has been absolutely positioned from. How can I un-constrain the flairText in such a way that its max-width would not be constrained by the parent it has been absolutely positioned from?

My main component:

import React, { FC } from 'react';import { Text } from 'react-native';import { barItemFlairStyles } from './styles/bar-item-flair';interface BarGraphItemFlairProps {  displayedValue: number;  maxDisplayedValue?: number;}export const BarItemFlair: FC<BarGraphItemFlairProps> = ({  displayedValue,  maxDisplayedValue}) => {  const ownStyles = barItemFlairStyles();  const displayedClampedValue = displayedValue;  return <Text style={ownStyles.flairText}>{displayedClampedValue}</Text>;};

Its style, in another file:

import { StyleSheet, TextStyle } from 'react-native';export const barItemFlairStyles = () =>  StyleSheet.create({    flairText: {      position: 'absolute',      top: -35,      textAlign: 'center',      backgroundColor: 'blue',    } as TextStyle,  });

I'd expect the absolutely positioned element to be able to grow beyond the parent if left and right are undefined

Explicitly setting left and right to undefined doesn't work. numOfLines={1} doesn't work as there is an ellipsis and the text is still not visible beyond the parent. Using flexShrink and things like that did not work as well. Setting flex to 1 did not work.

Initializing Text.defaultProps with Typescript

$
0
0

I just started rewriting my existing react-native project from js to typescript.To disable font scaling, I set Text.defaultProps.allowFontScaling to false at the beginning of App.js and it worked well.

import React from 'react';import { Text } from 'react-native';...if (Text.defaultProps == null) Text.defaultProps = {};Text.defaultProps.allowFontScaling=false; export default function App () {  . . .}

When I changed from App.js to App.tsx and ran tsc, I get following typescript error:

App.tsx:16:10 - error TS2339: Property 'defaultProps' does not exist on type 'typeof Text'.16 if (Text.defaultProps == null) Text.defaultProps = {};

I tried to search similar issues and typescript documents but failed. How can I solve this error?

Getting Expo Router to work with web navigation

$
0
0

I have an app I'm building using Expo and React Native, currently I'm building and deploying for web-based platforms (via Firebase Hosting) in order to get something out there before we go through the rigamarole of getting it through the app store approval processes.

The challenge I'm currently dealing with is trying to figure out how to get the router to handle web navigation events (specifically back, reload, and forward). I've tried single and static based rendering methods and in all cases web navigation results in a 'not found.'

The structure for my app is as follows:

root├── app│├── dist│├── app││├── (tabs) // the main content of the app│││├── _layout.tsx│││├── page.tsx│││└── anotherpage.tsx││├── (onboarding)│││├── _layout.tsx│││└── // onboarding specific pages go here││├── _layout.tsx││├── index.tsx││├── sign-in.tsx││└── create-account.tsx│├── components│├── providers│├── assets│└── app.json├── firebase //functions, dataconnect, etc│├── public //where firebase deploys hosting from

File contents:

/app/app.json

{"expo": {"scheme": "our-app",    ..."name": "Our App","slug": "ourApp","web": {"bundler": "metro","output": "static"    }  }}

/app/src/_layout.tsx

...export const unstable_settings = {  initialRouteName: "index",};export default function Root() {  return (<View>      ... //providers<RootNavigator />      ... //closing providers</View>  );}const RootNavigator = () => {  return (<Slot />);};

/app/src/(tabs)/_layout.tsx

export const unstable_settings = {  initialRouteName: 'page',};export default TabLayout(){  const { user, loading } = useAuth();  if(user) {  return (<Tabs><Tabs.Screen        name="page"        options={{ href: "/(tabs)/page",title: "Page"/> }}      /><Tabs.Screen        name="anotherPage"        options={{ href: "/(tabs)/anotherPage",title: "Another Page"/></Tabs>  );}

Any immediate thoughts?

Expo Image.prefetch works on Android but not iOS

$
0
0

My images were loading slow when using expo-image so I tried using image prefetch which works correctly on android but asset loading is still slow on ios. Has anyone experienced this or has any solution. The assets are s3 bucket urls and this preloading is working fine on android

import { Image } from "expo-image";import { useEffect, useState } from "react";import { assetUrls } from "../Constants/assetConstants";export const usePreloadImages = () => {  const [loaded, setLoaded] = useState<boolean>(false);  useEffect(() => {    let cancelled = false;    const preload = async () => {      try {        console.log("preloading mate");        await Promise.all(assetUrls.map((url) => Image.prefetch(url)));        if (!cancelled) setLoaded(true);      } catch (Err) {        console.error("Error loading images", Err);        if (!cancelled) setLoaded(true);      }    };    preload();    return () => {      cancelled = true;    };  }, []);  return loaded;};

also tried changing cachePolicy of IOS from default "disk" to "memory-disk" still images take some time to load and placeholders are shown


react native typescript 'string' is not assignable to parameter of type 'never.' in useNavigation

$
0
0

[I keep getting the error that says 'string' is not assignable to parameter of type 'never' in react native typescript and I don't know why. Can someone help me fix this bug.

Thank you in advance.

code picture

code snippet :

const loadReport = (id: string) => {    setPostId(id);    navigation.navigate('Report', {postId: id});}

I get an underline under 'Report'.

Why Toast message not appear in react-native-root-toast?

$
0
0

I implemented react-native-root-toast in my expo application, I am using expo 51, please refer below code to understand the problem

const bgColor = {'error': {        color: '#DA5C53',        iconName: <WarningIcon size="5" color="error.800" alignSelf="center" mr="5"/>,        iconColor: "error.800"    },'success': {        color: '#36AE7C',        iconName: <CheckCircleIcon size="5" color="success.800" alignSelf="center" mr="5"/>,        iconColor: "success.800"    },'info': {        color: '#4D96FF',        iconName: <InfoIcon size="5" color="info.800" alignSelf="center" mr="5"/>,        iconColor: "info.800"    }}export function ShowToast({    id,    status,    title,    description  }: toastType){    if(description == undefined){        description = "Some error occured"    }    console.log(description, "description")    let toast = Toast.show("Some error occured", {        duration: Toast.durations.LONG,        position: Toast.positions.BOTTOM,        backgroundColor: bgColor[status].color ,        delay: 2000,        hideOnPress: true,        opacity: 1,        shadow: true,        animation: true,    })    setTimeout(() => {        Toast.hide(toast);    }, 5000)}

I used different toastOptions but not working, help me How to fix it?

React Native Modal not showing properly when opening after focusing TextInput (Expo + KeyboardAwareScrollView) react-native-keyboard-controller

$
0
0

I’m developing a mobile app using React Native + Expo.On one screen, I wrap all my inputs inside KeyboardAwareScrollView.Besides the inputs, I also have a simple Modal that only contains some text and a button.

Packages used

"react-native-keyboard-controller": "^1.18.5","expo": "~52.0.47","react": "18.3.1","react-dom": "18.3.1","react-native": "0.76.9","expo-status-bar": "~2.0.1",...

Code example (ready to use)

app/_layout.tsx

import { KeyboardProvider } from 'react-native-keyboard-controller'import { Stack } from 'expo-router'import { StatusBar } from 'expo-status-bar'function RootLayout() {    return (<><KeyboardProvider><Stack                    screenOptions={{                        headerStyle: { backgroundColor: Colors.bgDark },                        headerTintColor: Colors.white,                        headerShadowVisible: false,                        navigationBarColor: Colors.bgDark,                    }}><Stack.Screen name="index" options={{ headerShown: false }} /></Stack></KeyboardProvider><StatusBar style="light" backgroundColor={'transparent'} /></>    )}

app/index.tsx

import { useState } from 'react'import { Button, Modal, StyleSheet, Text, TextInput, View } from 'react-native'import { KeyboardAwareScrollView } from 'react-native-keyboard-controller'import { SafeAreaView } from 'react-native-safe-area-context'export default function IndexPage() {    const [isShowModal, setIsShowModal] = useState(false)    return (<SafeAreaView style={{ flex: 1 }}><View style={styles.container}><KeyboardAwareScrollView                    showsVerticalScrollIndicator={false}                    contentContainerStyle={{                        flexGrow: 1,                        justifyContent: 'space-between',                    }}><View style={styles.inpustWrapper}><TextInput style={styles.input} placeholder="input1" /><TextInput style={styles.input} placeholder="input2" /><TextInput style={styles.input} placeholder="input3" /><TextInput style={styles.input} placeholder="input4" /><TextInput style={styles.input} placeholder="input5" /></View><Button onPress={() => setIsShowModal(true)} title="Open modal" /></KeyboardAwareScrollView></View><Modal visible={isShowModal}><View style={styles.modal}><Text>This text and button should appear</Text><Button title="close modal" onPress={() => setIsShowModal(false)} /></View></Modal></SafeAreaView>    )}const styles = StyleSheet.create({    container: { paddingHorizontal: 20, flex: 1 },    inpustWrapper: { gap: 16, marginBottom: 20, flex: 1 },    input: { borderWidth: 1, borderColor: 'black', height: 35, paddingHorizontal: 8 },    modal: {        backgroundColor: 'rgba(0,0,0,0.2)',        justifyContent: 'center',        alignItems: 'center',        flex: 1,        gap: 10,    },})

Steps to Reproduce the error

  1. Tap the “Open Modal” button → works fine, modal appears with text and button.
  2. Tap on any input → keyboard appears.
  3. Dismiss the keyboard.
  4. Tap the “Open Modal” button again → the modal appears, but the content is gone / invisible.

Question

How can I fix this so that the modal content always shows, even after focusing and dismissing a TextInput? Why does the modal fail to render in this scenario?

[Android][expo][@react-native-voice/voice] [TypeError: Cannot read property 'startSpeech' of null]

$
0
0

I'm trying to record user voice and transform it to text in react-native app, using expo, typescript, and @react-native-voice/voice package.

I have imported the library into my project, but when I try to launch the start or stop function, I get below errors:

TypeError: Cannot read property 'startSpeech' of nullTypeError: Cannot read property 'stopSpeech' of null

I have tried everything, but I don't understand why the library doesn't seem to load correctly...I am using Android 13. Perhaps there is a version incompatibility?

Please help, i dont find any solutions...

Here's the code for voice recording:

    import React, { useState } from 'react';    import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';    import Voice from '@react-native-voice/voice';    const SpeechToText = () => {        const [isRecording, setIsRecording] = useState(false);        const [speechText, setSpeechText] = useState('');        const onSpeechStartHandler = () => {            setIsRecording(true);            setSpeechText('');        };        const onSpeechEndHandler = () => {            setIsRecording(false);        };        const onSpeechResultsHandler = (event: any) => {            setSpeechText(event.value[0]);        };        const startSpeechToText = async () => {            try {                await Voice.start('en-US');                onSpeechStartHandler();            } catch (error) {                console.log(error);            }        };        const stopSpeechToText = async () => {            try {                await Voice.stop();                onSpeechEndHandler();            } catch (error) {                console.log(error);            }        };        return (<View style={styles.container}><TouchableOpacity                    style={styles.button}                    onPressIn={startSpeechToText}                    onPressOut={stopSpeechToText}                    disabled={isRecording}><Text style={styles.text}>Press and hold to speak</Text></TouchableOpacity><Text style={styles.speechText}>{speechText}</Text></View>        );    };

In app.json, here is my configuration:

    {"expo": {        [....]"android": {"adaptiveIcon": {"foregroundImage": "./assets/images/adaptive-icon.png","backgroundColor": "#ffffff"          },"permissions": ["android.permission.RECORD_AUDIO"          ]        },"plugins": [          ["@react-native-voice/voice",            {"microphonePermission": "CUSTOM: Allow $(PRODUCT_NAME) to access the microphone","speechRecognitionPermission": "CUSTOM: Allow $(PRODUCT_NAME) to securely recognize user speech"            }          ]        ]      }    }

here is my package.json:

"scripts": {"start": "expo start","android": "expo start --android","ios": "expo start --ios","web": "expo start --web","test": "jest --watchAll"      },"dependencies": {"@react-native-voice/voice": "^3.2.4","expo": "~48.0.11","expo-font": "~11.1.1","expo-linking": "~4.0.1","expo-permissions": "^14.1.1","expo-router": "^1.5.2","expo-speech": "^11.1.1","expo-splash-screen": "~0.18.1","expo-status-bar": "~1.4.4","expo-system-ui": "~2.2.1","expo-web-browser": "~12.1.1","react": "18.2.0","react-dom": "18.2.0","react-native": "0.71.6","react-native-keyboard-aware-scroll-view": "^0.9.5","react-native-safe-area-context": "4.5.0","react-native-screens": "~3.20.0","react-native-vector-icons": "^9.2.0","react-native-web": "~0.18.10"      },"devDependencies": {"@babel/core": "^7.20.0","@types/react": "~18.0.14","@types/react-native": "^0.71.5","react-test-renderer": "18.2.0","typescript": "^4.9.4"      },"private": true    }```

How to refetch react openAI react query queries

$
0
0

I am working on a react native app that is using openapi-react-query in order to enforce the type safety across backend and mobile, my struggle is how to refetch queries (in a component other than the one where the query is defined) using this tool, as this action is pretty straightforward when using the @tanstack/react-query by using the query client and refetch/invalidate queries by their keys, but in my case I haven't the option to define a key for the queries and the queryHash doesn't seem to be working in this specific case.

Any help is appreciated!

This is an example of a query:

  return $api.useQuery('get','/profile',    {},    {      queryHash: QUERY_KEYS.GET_USER_DETAILS,      staleTime: FIFTEEN_SECONDS_IN_MS,    },

How to solve internet connection issues with expo go on phone?

$
0
0

When I start npm in VS Code along with the API, everything runs fine in the browser on my computer.However, on my phone, it doesn’t work properly. When I scan the QR code, it takes a long time to load and always shows a message saying that the internet connection is the problem. I tried changing phones and Wi-Fi networks several times, but nothing changed.I even updated the npm version in my environment, but the issue persists — it still won’t open on my phone.

Look for react native solution that we can open the Floating window outside the App even when the app is closed or minimize

$
0
0

Look for react native solution that we can open the Floating window outside the App even when the app is closed or minimize


Expo monorepo build fails with module not found

$
0
0

I am using react native and expo eas in my monorepo.The app lives inclients/mobile/<react native app>My metro.config.js lives inside the mobile folder

const { getDefaultConfig } = require('expo/metro-config');const path = require('path');// Find the project and workspace directoriesconst projectRoot = __dirname;// This can be replaced with `find-yarn-workspace-root`const monorepoRoot = path.resolve(projectRoot, '../..');const config = getDefaultConfig(projectRoot);// 1. Watch all files within the monorepoconfig.watchFolders = [monorepoRoot];// 2. Let Metro know where to resolve packages and in what orderconfig.resolver.nodeModulesPaths = [  path.resolve(projectRoot, 'node_modules'),  path.resolve(monorepoRoot, 'node_modules'),];module.exports = config;

I am using typescript as well.

I am getting this error

Error: Unable to resolve module @react-native-firebase/analytics from /home/expo/workingdir/build/node_modules/@react-native-firebase/crashlytics/lib/handlers.js: @react-native-firebase/analytics could not be found within the project or in these directories:  ../../node_modules  node_modules  ../../node_modules  17 |  18 | import { isError, once } from '@react-native-firebase/app/lib/common';> 19 | import { getAnalytics, logEvent } from '@react-native-firebase/analytics';

I am not sure why. Any help would be much appreciated.

React Native TTS played sound twice on iOS simulator, and only once on Android. Why?

$
0
0

Consider a mobile payment app. Once the transaction is succesfully paid, then a notification sound will be played, something like "Hello the transaction is succesfully paid.".

Here's my attempt to do that:

const [voiceIsAlreadyPlayed, setVoiceIsAlreadyPlayed] = useState<boolean>(false);  const {id} = route.params as {    id: string;  };  const {transaction, fetchTransaction} = useTransaction();    useEffect(() => {    id && fetchTransaction(id);    if (transaction?.total != undefined){     setTimeout(() => {        if (AppState.currentState === 'active') {          if (Platform.OS == 'ios'){              Tts.getInitStatus().then(() => {                        Tts.setDefaultLanguage('en');                        if (!voiceIsAlreadyPlayed){                          Tts.speak("Payment succesful.");                          setVoiceIsAlreadyPlayed(true);                        }                      }).catch(err => {                        console.error('TTS init error: ', err);                      });          } else if (Platform.OS == 'android') {              Tts.getInitStatus().then(() => {             Tts.setDefaultLanguage('en');            Tts.speak("Payment succesful.");          }).catch(err => {            console.error('TTS init error: ', err);          });          }        } else {          console.log('App not in foreground, skipping TTS');        }      }, 1250);     }  }, [id, transaction?.total]);

On Pixel 4 emulator (Android 15) the sound is only played once. Works as expected. But on iOS 18 simulator, it's always played twice. So perhaps adding a voiceIsAlreadyPlayed flag could prevent that. But it doesn't work.

How to properly fix this, so the sound is only played once?

I'm on RN 0.71.0 and react-native-tts 4.1.1

How to properly lift any container on pressing the input bar in newer Android version and older version all devices? (KeyboardAvoidingView)

$
0
0

Very simple question.

I have pixel 6a below code works everywhere expect the real pixel device 6a which has android 16.

It works on Redmi note 11 which has android 11 and on Emulator which is pixel 6 (android 14). But not on the pixel device. When I use the below code

<KeyboardAvoidingView  behavior={Platform.OS === 'ios' ? 'padding' : undefined}  style={{ flex: 1 }}  enabled>

Sometimes the container goes up but just up to the input bar, only input bar gets hidden. But meanwhile when I turn off the screen and unlock my pixel 6a mobile, it gets corrected. I just want a global solution, can anyone help. I don't know what is happening when turning off and on the screen.

This is my current code. It works but with a bug like gaps being produced often. But works but not smoothly.

const keyboardOffset = isKeyboardVisible ?  headerHeight : headerHeight + insets.bottom + 23;  return (<KeyboardAvoidingView    keyboardVerticalOffset={keyboardOffset}      behavior={Platform.OS === 'ios' ? 'padding' : undefined}      style={{ flex: 1 }}      enabled><SafeAreaView style={styles.container}>        {/* Header */}<View style={styles.header}></View><FlatList /><MessageInput receiverUsername={selectedReceiverUsername || ''} status={status} /></SafeAreaView></KeyboardAvoidingView>  )

How to get rid of this error in React native

$
0
0

Does anyone else get this error and just have to ignore it constantly? Unexpected text node: . A text node cannot be a child of a <View>. There's not an extra '.' somewhere in my code as it suggests. there may be in some package that I'm using. I feel like every project I make, it inevitably gets this error and I can't trace it back to any piece of code that I've written. I could be wrong but I feel like I'm going crazy so does this happen to anyone else?

I've tried commenting out every line of code and it's always some component or something that I find to be throwing the error but I can never find the actual 'period' that is causing the error. It's so annoying

axios giving ERROR API ERROR: [AxiosError: Network Error] in react native

$
0
0

I am new to react native, and I am trying to submit an API using axios in react native, but I am getting the following error:

ERROR  API ERROR: [AxiosError: Network Error]

I dont know what this is or how I can fix this.

My backend is run on Laravel, I know when i try to call that, it does not hit my backend/server

The api works on the browser, even on the emulator browser.

Here is the API: http://loipay2.council-app.revsol.io/api/rentals

Here is the code i put in react native:

export default function LanguageSettings() {  const { language, setLanguage } = useLanguage();  const [selectedLanguage, setSelectedLanguage] = useState(language);  const selectLanguage = async (lang: "English" | "Dhivehi") => {    setSelectedLanguage(lang);    setLanguage(lang);  };  useEffect(() => {    const fetchData = async () => {      axios        .get("http://loipay2.council-app.revsol.io/api/rentals", {          withCredentials: true,          headers: {"Content-Type": "application/json",            Accept: "application/json",          },        })        .then((res) => console.log("API OK:", res.data))        .catch((err) => console.error("API ERROR:", err));    };    fetchData();  }, []);

Expo Router - How to wrap Stack in a layout

$
0
0

I would like to develop an application in React Native, but I'm having problems with layouts. I would like to create a layout and surround my application with it to use it only once. In the past, I created a MainLayout component that I used for each screen:

MainLayout.tsx

  return (<SafeAreaView style={styles.body}><StatusBar style="dark" hidden />        {children}</SafeAreaView>  );

But I would like to find a less repetitive way. I tried this structure, but it doesn't work. For example, the background is not applied (it's only applied to the StatusBar):

Homepage

Folder structure:

app/├── _layout.tsx├── index.tsx├── (screens)/├── about/└── index.tsx

app/_layout.tsx

export default function RootLayout() {  return (<SafeAreaView style={styles.container}><Slot /></SafeAreaView>  );}

app/index.tsx

export default function App() {  return (<View style={styles.container}><Text>Title</Text><TouchableOpacity onPress={() => router.push("/about")}><Text>Start</Text></TouchableOpacity></View>  );}

I also tried to change my index.tsx like a router file:

export default function App() {  return (<Stack><Stack.Screen name="/(screens)/index" /></Stack>  );}

I have obviously added an index.tsx file to my group (screens). However, even if my style rules are correctly applied, no content is rendered.

Property * does not exist on type typeof * - static parent method

$
0
0

React Native, TypeScript code JS(non-TS) ORM module:

Parent BaseModel:

export default class BaseModel {  static createTable() {    ...  }  ...

My model of Animal does NOT redefine the method, it's just defined as:
export default class Animal extends BaseModel { ...

Now this code await Animal.createTable(); actually works, but VSCode TypeScript checker gives following error in code:

Property 'createTable' does not exist on type 'typeof Animal'.ts(2339)

Is this the editor/checker issue? Or should the JS/TS code be defined somehow better?


Failed to obtain view for PanGestureHandler in functional component

$
0
0

I'm working on a React Native app using Expo and react-native-gesture-handler.When I try to use PanGestureHandler inside my App.tsx, I get the following error at runtime:

ERROR [Error: [Gesture Handler] Failed to obtain view for PanGestureHandler.Note that old API doesn't support functional components.]

Here’s my simplified App.tsx code:

import React from 'react';import './global.css';import { StatusBar } from 'expo-status-bar';import RootNavigation from './src/navigation';import { View, Text, Platform, StyleSheet, ActivityIndicator } from 'react-native';import { GestureHandlerRootView, PanGestureHandler, PanGestureHandlerGestureEvent } from 'react-native-gesture-handler';import { useFonts, Inter_400Regular } from '@expo-google-fonts/inter';export default function App() {  const [fontsLoaded] = useFonts({ Inter_400Regular });  if (!fontsLoaded) {    return (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><ActivityIndicator size="large" /></View>    );  }  const onGestureEvent = (e: PanGestureHandlerGestureEvent) => {    // no-op  };  return (<GestureHandlerRootView style={styles.root}><View style={styles.boxContainer}><PanGestureHandler onGestureEvent={onGestureEvent}><View style={styles.box}><Text>Drag me (no-op)</Text></View></PanGestureHandler></View></GestureHandlerRootView>  );}const styles = StyleSheet.create({  root: { flex: 1 },  boxContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' },  box: { width: 200, height: 200, alignItems: 'center', justifyContent: 'center', backgroundColor: '#eee' },});

I have wrapped everything inside GestureHandlerRootView as recommended by the docs, but the error persists.

Environment:

  • React Native: 0.81.4
  • Expo SDK: 54
  • react-native-gesture-handler: ~2.28.0

What I've tried:

  • Verified that GestureHandlerRootView wraps the entire app.
  • Cleaned build cache (npx expo start -c).
  • Tried moving PanGestureHandler to a separate component.

The error seems to say that the "old API doesn't support functional components" — but I'm using the latest versions and a functional component for App.

Can I pass boolean values through search params using Expo Router's useLocalSearchParams?

$
0
0

I'm trying to pass a boolean flag when navigating between screens with Expo Router and read it with useLocalSearchParams, but the value I receive is a string (e.g. "true" / "false") rather than a boolean true / false. Is there a supported way to pass native boolean values via search params, or should I always stringify/parse them?

Pass a boolean when navigating and read it as a boolean on the destination screen.

How to properly receive a message on ReactNative app via WebSocket?

$
0
0

We use OneSignal to implement push notifications for our ReactNative app. So far works fine on Android & iOS devices... until we need to support a particular Android device without Google Play Services installed. Perhaps one of the alternatives is WebSocket.

I tried the implementation described in this: A charming romance between WebSocket and React Native

useWebsocket.ts

import { useEffect, useRef, useState } from 'react';const useWebSocket = (  onMessage = () => {},  onError = () => {},  onClose = () => {}) => {  const [isWebSocketConnected, setWebSocketConnected] = useState(false);  const ws = useRef(null);  const reconnectIntervalRef = useRef(1000);  const wsurl = 'ws://echo.websocket.org'; // replace it with your URL  const connectWebSocket = () => {    try {      // Create a WebSocket connection      ws.current = new WebSocket(wsurl);      // WebSocket event listeners      ws.current.onopen = () => {        setWebSocketConnected(true);        console.log('ws connected');        reconnectIntervalRef.current = 1000; // Reset reconnection interval on successful connection      };      ws.current.onmessage = (event) => {        onMessage(event.data);      };      ws.current.onerror = (error) => {        onError(error);      };      ws.current.onclose = (event) => {        setWebSocketConnected(false);        console.log('ws disconnected');        onClose(event);        // Attempt to reconnect        setTimeout(() => {          reconnectIntervalRef.current = Math.min(            reconnectIntervalRef.current * 2,            30000          ); // Exponential backoff, max 30 seconds          connectWebSocket();        }, reconnectIntervalRef.current);      };    } catch (error) {      console.log(error);    }  };  useEffect(() => {    connectWebSocket();    // Clean up WebSocket connection on component unmount    return () => {      if (ws.current) {        ws.current.close();      }    };  }, [wsurl]);  return isWebSocketConnected;};export default useWebSocket;

And the test screen, which only the displays the connection status and the message received on console.

import {useEffect, useState} from 'react';;import {StackActions, useNavigation, useRoute} from '@react-navigation/native';import useWebSocket from '../../hooks/useWebsocket';export default function TestWebSocketPage() {  const navigation = useNavigation();  const [messages, setMessages] = useState([]);  const handleOnMessage = (message) => {    setMessages((prevMessages) => [...prevMessages, message]);    console.log('ws message: '+message);  };  const handleOnError = (error) => {    console.error('WebSocket error:', error);  };  const handleOnClose = (event) => {    console.log('WebSocket closed:', event);  };  const isWebSocketConnected = useWebSocket(handleOnMessage, handleOnError, handleOnClose);  return (<AppContainer backgroundColor={COLORS.white}><SafeAreaView style={{flex: 1}}><AppHeader          title="WebSocket Demo"          hideBack={false}          indicatorRight={true}          color={COLORS.primary}        /></SafeAreaView></AppContainer>  );}

Now let's test. Open https://websocketking.com. and input wss://echo.websocket.org as your websocket URL.enter image description here

And this is what I see on my console:

LOG  ws connectedERROR  WebSocket error: {"isTrusted": false, "message": null}LOG  ws disconnectedLOG  WebSocket closed: {"code": 1006, "isTrusted": false, "reason": null}ERROR  WebSocket error: {"isTrusted": false, "message": null}LOG  WebSocket closed: {"code": 1006, "isTrusted": false, "reason": null}ERROR  WebSocket error: {"isTrusted": false, "message": null}LOG  WebSocket closed: {"code": 1006, "isTrusted": false, "reason": null}LOG  ws connected

What's wrong here? I'm on RN 0.71.0 and Android 15 emulator.

How to properly receive WebSocket messages using react-use-websocket?

$
0
0

I'm still trying to figure out how to receive message on my ReactNative app using Websocket. Now with react-use-websocket library.

Here's my code:

import useWebSocket, { ReadyState } from 'react-use-websocket';export default function WebSocketTestPage() {  const navigation = useNavigation();  const [messageHistory, setMessageHistory] = useState([]);  const [socketUrl, setSocketUrl] = useState('wss://echo.websocket.org');  const {    sendMessage,    sendJsonMessage,    lastMessage,    lastJsonMessage,    readyState,    getWebSocket,    } = useWebSocket(socketUrl, {        onOpen: () => console.log('websocket opened'),        //Will attempt to reconnect on all close events, such as server shutting down        shouldReconnect: (closeEvent) => true,        });  const connectionStatus = {    [ReadyState.CONNECTING]: 'Connecting',    [ReadyState.OPEN]: 'Open',    [ReadyState.CLOSING]: 'Closing',    [ReadyState.CLOSED]: 'Closed',    [ReadyState.UNINSTANTIATED]: 'Uninstantiated',  }[readyState];  useEffect(() => {    console.log('connection status: '+connectionStatus);  },[connectionStatus]);  useEffect(() => {    if (lastMessage){      console.log('lastMessage: '+lastMessage.data);    } else {       console.log('lastMessage: null');    }  },[lastMessage])  return (<AppContainer backgroundColor={COLORS.white}><SafeAreaView style={{flex: 1}}><AppHeader          title="Websocket Test"          hideBack={false}          indicatorRight={true}          color={COLORS.primary}          rightComponent={<Pressable              onPress={() => {                sendMessage('asdasdasda');               }}><IconQuestionBlue /></Pressable>          }</SafeAreaView></AppContainer>  );}

Tried sending messagea a few times via websocketking.comenter image description here

This is the output (tested on Pixel 4 XL emulator running Android 15):

LOG  connection status: ConnectingLOG  lastMessage: nullLOG  websocket openedLOG  connection status: OpenLOG  lastMessage: Request served by 4d896d95b55478LOG  lastMessage: asdasdasdaLOG  lastMessage: asdasdasdaLOG  lastMessage: asdasdasdaLOG  lastMessage: asdasdasda

Request served by 4d896d95b55478 is received from websocketking.com, and so far there's only 1 line (yet the messages sent is > 1). Interestingly, there are a few lastMessage: asdasdasda lines, which is the result of calling sendMessage on click. Perhaps there are some misunderstanding. Why there's only a message recieved from websocketking.com? I'm on RN 0.71.0, BTW.

Why is React Native debugger opening in x86 version of Chrome, and not arm64?

$
0
0

I'm using react native with Expo/Hermes on a mac M1. When I open the app and hit "open debugger" it opens the debugger in an x86 version of chrome, which is extremely slow. Why is this happening?

I don't have that version of chrome installed, so I have no idea where it's coming from.

Chrome version installed: 120.0.6099.129 (Official Build) (arm64)

React native: 0.74.5

Expo: 51

Steps to reproduce:

  1. run npx expo run:ios --device
  2. App runs on device
  3. Press m │ toggle menu
  4. Press "Debug Remote JS" on device

websocket message sent from Centrifugo appears on HTML and not on ReactNative app

$
0
0

I used Centrifugo to send webocket message.enter image description here

Here's HTML page that receives the message, and it works.

<html><head><title>Centrifugo quick start</title></head><body><div id="counter">-</div><script src="https://unpkg.com/centrifuge@5.4.0/dist/centrifuge.js"></script><script type="text/javascript">            const container = document.getElementById("counter");            const centrifuge = new Centrifuge("ws://centrifugo.xxxxx.xxxxx/connection/websocket",                {                    token: "xxxxxxxxxxxxxxxxxxxx",                },            );            centrifuge                .on("connecting", function (ctx) {                    console.log(`connecting: ${ctx.code}, ${ctx.reason}`);                })                .on("connected", function (ctx) {                    console.log(`connected over ${ctx.transport}`);                })                .on("disconnected", function (ctx) {                    console.log(`disconnected: ${ctx.code}, ${ctx.reason}`);                })                .connect();            const sub = centrifuge.newSubscription("$ojire", {                token: "xxxxxxxxxx,            });            sub.on("publication", function (ctx) {                container.innerHTML = ctx.data.value;                document.title = ctx.data.value;            })                .on("subscribing", function (ctx) {                    console.log(`subscribing: ${ctx.code}, ${ctx.reason}`);                })                .on("subscribed", function (ctx) {                    console.log("subscribed", ctx);                })                .on("unsubscribed", function (ctx) {                    console.log(`unsubscribed: ${ctx.code}, ${ctx.reason}`);                })                .subscribe();</script></body></html>

enter image description here

Now let's put this in React (I'm on RN 0.71.0 and Android 15 emulator). After sending another message, I could only see this on terminal:

 LOG centrifuge connecting: 0, connect called LOG centrifuge subscribing: 0, subscribe called

Where are the rest? What's wrong here? Already had <uses-permission android:name="android.permission.INTERNET" /> on AndroidManifest.xml

How to use navigate to move to another page from App.tsx?

$
0
0

I use Centrifugo to deliver push notifications to our app. So far, displaying the message using Toast works fine. Now I want to do something different, something like navigate to a certain page.

Here's the part of App.tsx

import { Centrifuge } from 'centrifuge';import Toast from 'react-native-toast-message';import { useNavigation } from '@react-navigation/native';const navigation: any = useNavigation();useEffect(() => {    const centrifuge = new Centrifuge("wss://centrifugo.xxxxx.xxxxxx/connection/websocket", {            token: "xxxxxxxxxxxxxxxxxxxx"        });        centrifuge.on('connecting', function (ctx) {            console.log(`centrifuge connecting: ${ctx.code}, ${ctx.reason}`);        }).on('connected', function (ctx) {            console.log(`centrifuge connected over ${ctx.transport}`);        }).on('disconnected', function (ctx) {            console.log(`centrifuge disconnected: ${ctx.code}, ${ctx.reason}`);        }).connect();        const sub = centrifuge.newSubscription("xxxxx", {            token: 'xxxxxxxxxxxxxxxxxxxx'        });         sub.on('publication', function (ctx) {           // websocket returns this JSON: {"title":"xxxxx", "message":"xxxxxx","transaction_id":"xxxxxx}             Toast.show({              type: "success",              text1: ctx.data['message']            });            navigation.navigate('DetailHistory', {              id: ctx.data['transaction_id']            });        }).on('subscribing', function (ctx) {            console.log(`centrifuge subscribing: ${ctx.code}, ${ctx.reason}`);        }).on('subscribed', function (ctx) {            console.log('centrifuge subscribed', ctx);        }).on('unsubscribed', function (ctx) {            console.log(`centrifuge unsubscribed: ${ctx.code}, ${ctx.reason}`);        }).subscribe();        return () => {            centrifuge.disconnect();            console.log('Centrifuge client disconnected on cleanup.');            };        //centrifuge.connect();  },[])

The code will crash like thisenter image description here

The cause is this line: const navigation: any = useNavigation(); (once the navigation stuffs are commented, the code runs fine). So how to navigate to different page from App.tsx?


Error: Cannot find module '../lightningcss.win32-x64-msvc.node' ADRIAN [duplicate]

$
0
0

Require stack:

  • D:\codebility_projects\SubTrack\node_modules\react-native-css-interop\node_modules\lightningcss\node\index.js
  • D:\codebility_projects\SubTrack\node_modules\react-native-css-interop\dist\css-to-rn\index.js
  • D:\codebility_projects\SubTrack\node_modules\react-native-css-interop\dist\metro\index.js
  • D:\codebility_projects\SubTrack\node_modules\nativewind\dist\metro\index.js
  • D:\codebility_projects\SubTrack\metro.config.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\node_modules\import-fresh\index.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\dist\loaders.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\dist\createExplorer.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\dist\index.js
  • D:\codebility_projects\SubTrack\node_modules\metro-config\src\loadConfig.js
  • D:\codebility_projects\SubTrack\node_modules\metro-config\src\index.js
  • D:\codebility_projects\SubTrack\node_modules@expo\metro\metro-config\index.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\server\metro\instantiateMetro.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\server\metro\MetroBundlerDevServer.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\server\DevServerManager.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\startAsync.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\index.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\bin\cli
  • D:\codebility_projects\SubTrack\node_modules\expo\bin\cliError: Cannot find module '../lightningcss.win32-x64-msvc.node'Require stack:
  • D:\codebility_projects\SubTrack\node_modules\react-native-css-interop\node_modules\lightningcss\node\index.js
  • D:\codebility_projects\SubTrack\node_modules\react-native-css-interop\dist\css-to-rn\index.js
  • D:\codebility_projects\SubTrack\node_modules\react-native-css-interop\dist\metro\index.js
  • D:\codebility_projects\SubTrack\node_modules\nativewind\dist\metro\index.js
  • D:\codebility_projects\SubTrack\metro.config.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\node_modules\import-fresh\index.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\dist\loaders.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\dist\createExplorer.js
  • D:\codebility_projects\SubTrack\node_modules\cosmiconfig\dist\index.js
  • D:\codebility_projects\SubTrack\node_modules\metro-config\src\loadConfig.js
  • D:\codebility_projects\SubTrack\node_modules\metro-config\src\index.js
  • D:\codebility_projects\SubTrack\node_modules@expo\metro\metro-config\index.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\server\metro\instantiateMetro.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\server\metro\MetroBundlerDevServer.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\server\DevServerManager.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\startAsync.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\src\start\index.js
  • D:\codebility_projects\SubTrack\node_modules\expo\node_modules@expo\cli\build\bin\cli
  • D:\codebility_projects\SubTrack\node_modules\expo\bin\cliat Function._resolveFilename (node:internal/modules/cjs/loader:1383:15)at defaultResolveImpl (node:internal/modules/cjs/loader:1025:19)at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1030:22)at Function._load (node:internal/modules/cjs/loader:1192:37)at TracingChannel.traceSync (node:diagnostics_channel:322:14)at wrapModuleLoad (node:internal/modules/cjs/loader:237:24)at Module.require (node:internal/modules/cjs/loader:1463:12)at require (node:internal/modules/helpers:147:16)at Object. (D:\codebility_projects\SubTrack\node_modules\react-native-css-interop\node_modules\lightningcss\node\index.js:21:22)at Module._compile (node:internal/modules/cjs/loader:1706:14)

SOLUTION: just download this "https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170"