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

Expo Location Error: Not authorized to use background location services

$
0
0

I'm creating a app that needs the current location of the user and need to run in real time. i'm using the Location.startLocationUpdatesAsync() from expo but i'm getting the error below.The app.json is already configured and in the phone i accept the location permission. someone can tell me why i'm getting the error?

app.json

"ios": {"supportsTablet": true,"bundleIdentifier": "com.ourtor.ourtorapp","buildNumber": "0.0.8","infoPlist": { "UIBackgroundModes": [ "location", "fetch" ] }    },"android": {"adaptiveIcon": {"foregroundImage": "./assets/adaptive-icon.png","backgroundColor": "#FFFFFF"      },"permissions": ["ACCESS_COARSE_LOCATION","ACCESS_FINE_LOCATION","ACCESS_BACKGROUND_LOCATION"      ]    },

map.ts

  useEffect( () => {    Location.requestPermissionsAsync().then( async (res) => {      if(res.status === "granted") {        console.log('granted')        await Location.startLocationUpdatesAsync('get-location', {          accuracy: Location.Accuracy.Balanced        })      }    });  }, [])

console android

granted[Unhandled promise rejection: Error: Not authorized to use background location services.]

console ios

grantedBackground Location has not been configured. To enable it, add 'location' to 'UIBackgroundModes' in Info.plist file.

How to define TypeScript Type for Object with both static and dynamic key? [duplicate]

$
0
0

I have a normalized redux structure addressesState as below. I need to define the type of that as specified in the comments

interface iAddressItem {    firstName: string;    lastName: string;    street: string;}const addressesState = {    // key "ids" is static    // value is Array<string>    ids: ["1345", "1346"],    // typeof key is string and it is dynamic    // typeof value is iAddressItem"1345": {        firstName: "Cinta",        lastName: "Riardo",        street: "Cake Street 34",    },    // typeof key is string and it is dynamic    // typeof value is iAddressItem"1346": {        firstName: "Nosipho",        lastName: "Tracey",        street: "Baker Street 42",    },};

I tried to define the type of addressesState as below:

type AddressesType = {    [key in string | number]?: iAddressItem;} & {    ids?: Array<number>;};

But when I'm initializing the redux state as:

const initalAddressesState: AddressesType = {    ids: []}

I'm getting the error:

Type '{ ids: never[]; }' is not assignable to type 'AddressesType'.  Type '{ ids: never[]; }' is not assignable to type '{ [x: string]: iAddressItem | undefined; [x: number]: iAddressItem | undefined; }'.    Property 'ids' is incompatible with index signature.      Type 'never[]' is missing the following properties from type 'iAddressItem': firstName, lastName, street(2322)

Any bits of help or insights would be great

'React-Native-Share' Library fails to compile on Web

$
0
0

I've been creating react-native app to share text or images to social platforms.I've used React-Native-Share library to serve the purpose of my application.This library is working fine for iOS & Android but when I'm running it on Web.I'm facing compiling failed error (Syntax Error). It seems like React-Native-Web cannot parse the syntax used by this library.As far as I researched on it. I think I need to setup webpack.config.js for this to work, but as I've never did this before so not sure how it works and how to set it up.

Please see the attached screenshotSyntax Error

Thank you in advance :)

How to filter db data based on a JSONB column in KNEX using Typescript / Javascript

$
0
0

Please help point me in the right direction: I have a jsonb column in one of my tables. It saves stringified data like this:

entry: {    1: "data1",    2: "data2"}

If I want to get entries whose key 1 is data1, how do I write the query?Below throws an sql error:

sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '['1'] = 'data1' limit 500' at line 1",

Here is what I used in the model:

return await db(db_table).select('*').limit(per_page).where('form_id', form_id).whereRaw("entry->>[?] = ?",['1', 'data1']); // issue is here

How can I construct that last line to search json field/column and return all filtered rows in the table where key 1 is equal to data1?Thank you!

this keyword is returning true/false instead of element object in react/ react-native

$
0
0
I recently started learning/coding in react and I need help in fixing a bug. I have 2 checkboxes on my application screen but those checkboxes should work like radio button which means when I check one checkbox, other checkbox should automatically uncheck. I tried using below options but its returning true/false instead of element object
<View style={{ flexBasis: '50%' }}><PrimaryCheckBox                    onPress={this.toggleForPrimaryCheckBox}                    checkBoxValue='forPrimary'                    checkBoxLabel='forPrimary'                    checkBoxViewStyle={stylesheet.CheckboxViewStyle}                    checkBoxTextStyle={stylesheet.CheckboxTextStyle}                  /></View><View style={{ flexBasis: '50%' }}><PrimaryCheckBox                    onPress={() => this.toggleForDependentCheckBox.bind(this)}                    checkBoxValue='forDependent'                    checkBoxLabel='forDependent'                    }                    checkBoxViewStyle={                      stylesheet.CheckboxViewStyle                    }                    checkBoxTextStyle={                      stylesheet.CheckboxTextStyle                    }                  /></View>

Note: PrimaryCheckBox component is a custom component

I tried the below options and none worked

1. onPress={() => this.toggleForDependentCheckBox.bind(this)}2. onPress={this.toggleForDependentCheckBox.bind("forDependent",e)} //threw error that e is not defined3.  onPress={this.toggleForDependentCheckBox}     public toggleForPrimaryCheckBox = (e: MouseEvent) => {    console.log(e);  //returns true when checked and false when unchecked    console.log(this) // returns class component }

Can someone please help what mistake I am doing?I am trying to use single function for both elements so that based on selected element, I can uncheck other element and perform other logic

<View style={{ flexBasis: '50%' }}><PrimaryCheckBox                    onPress={this.togglePrimaryDependentCheckBox}                    checkBoxValue='forPrimary'                    checkBoxLabel='forPrimary'                    checkBoxViewStyle={stylesheet.CheckboxViewStyle}                    checkBoxTextStyle={stylesheet.CheckboxTextStyle}                  /></View><View style={{ flexBasis: '50%' }}><PrimaryCheckBox                    onPress={this.togglePrimaryDependentCheckBox}                    checkBoxValue='forDependent'                    checkBoxLabel='forDependent'                    }                    checkBoxViewStyle={                      stylesheet.CheckboxViewStyle                    }                    checkBoxTextStyle={                      stylesheet.CheckboxTextStyle                    }                  /></View>

Thanks in advance

how to display Quiz randomly and without duplication in react native

$
0
0

everyone.I try to make Quiz app randomly and without duplication in React Native .Successfully Quiz are displayed randomly.But I don't know how to display them without duplication .I am very new to learn React Native.If you have any idea to solve this issue , please help me .I use Mac book pro , Visual Code Studio and React Native.

I write the code as below .

export function App() { const questions = [  {   questionText: "city",  answerOptions: [  { answerText: "canada", isCorrect: false },  { answerText: "USA", isCorrect: false },  { answerText: "Napoli", isCorrect: true },  { answerText: "Brazil", isCorrect: false },  ],  }, { questionText: "country", answerOptions: [ { answerText: "Paris", isCorrect: false }, { answerText: "London", isCorrect: false }, { answerText: "Spain", isCorrect: true }, { answerText: "Rome", isCorrect: false }, ], }, { questionText: "color", answerOptions: [ { answerText: "dog", isCorrect: false }, { answerText: "cat", isCorrect: false }, { answerText: "blue", isCorrect: true }, { answerText: "tiger", isCorrect: false }, ], }, { questionText: "currency", answerOptions: [ { answerText: "cash", isCorrect: false }, { answerText: "money", isCorrect: false }, { answerText: "Pond", isCorrect: true }, { answerText: "card", isCorrect: false }, ], }, ]; const randomQuestions = questions[Math.floor(Math.random() * questions.length)]; return (<View style={styles.container}><Text style={styles.question}>{randomQuestions.questionText}</Text><Text style={styles.answer}>{randomQuestions.answerOptions[0].answerText}</Text><Text style={styles.answer}>{randomQuestions.answerOptions[1].answerText}</Text><Text style={styles.answer}>{randomQuestions.answerOptions[2].answerText}</Text><Text style={styles.answer}>{randomQuestions.answerOptions[3].answerText}</Text></View>);};

react-native-web typescript error when passing props to svg component

$
0
0

I've configured metro and webpack to import svgs like so:

import PlayIcon from '../../assets/icons/play-icon.svg';...return () => <PlayIcon />

The problem is when I try to pass props, I get a typescript error on both my editor (vscode) and webpack terminal:

Type '{ width: number; height: number; }' is not assignable to type 'IntrinsicAttributes'.  Property 'width' does not exist on type 'IntrinsicAttributes'

this is my tsconfig.json

{"compilerOptions": {"target": "esnext","module": "esnext","lib": ["es6"    ],"allowJs": true,"jsx": "react","noEmit": true,"isolatedModules": true,"strict": false,"moduleResolution": "node","baseUrl": "./","allowSyntheticDefaultImports": true,"esModuleInterop": true,"resolveJsonModule": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"noFallthroughCasesInSwitch": true  },"exclude": ["node_modules","babel.config.js","metro.config.js","jest.config.js"  ],"include": ["src","src/types/definitions/svg.d.ts"  ]}

and src/types/definitions/svg.d.ts:

declare module '*.svg' {    import { SvgProps } from 'react-native-svg';    const content: React.FC<SvgProps>;    export default content;}// also tried, amongst othersdeclare module '*.svg' {    const content: any;    export default content;}

Things I've tried:

  1. Passing "**/*.svg" to tsconfig.json.exclude
  2. Different ways to declare the svg module definitions. The one I posted here is what I've found in many tutorials and references.

So what am I doing wrong?

Is there a way to find length of FlatList in React native

$
0
0

I have a list of ltem, I want to know the size of list I am using FlatList to display the Curosel item in horizental scroll view please some.help


react native app crushes after using setState

$
0
0

I'm trying to build a custom password component which menage is own state, now the problem is that when I click on TextInput.icon the app stop responding. P.s the this component is running inside of a functional componet. this is my code:

// This Components is the used to replace the navigation bar from ract native navigation using the header optionsimport React, { Component } from 'react';import {  View } from 'react-native';import {  TextInput } from 'react-native-paper';interface DeliverText{  onChangeText:(text:string)=>void;  value:string;}interface SecureState {    secure:boolean;} export class Password extends Component<DeliverText,SecureState>{     constructor(props:DeliverText){         super(props);         this.state={secure:true}     }     render(){       const {secure} = this.state;        console.log(`reloading secure:${secure}`);        return (<View><TextInput                     label="Password"                     value={this.props.value}                    onChangeText={this.props.onChangeText}                    secureTextEntry={secure}                    right ={<TextInput.Icon name={secure?"eye":"eye-close"} onPress={()=>{this.setState({secure:!secure})}} />                    }           /></View>        );     } }

How to load script in React-native?

$
0
0

I want to load the script in my React native project. I would like to make a custom Razorpay payment. and we use typescript. I tried many ways but I am not getting a solution. Please give me a solution if it works then I accept your answer Anyone here with a solution for this? Thanks in Advance. Here is my code.

<script type="text/javascript" src="https://checkout.razorpay.com/v1/razorpay.js"></script>var razorpay = new Razorpay({            key: '<Key>',             image: 'https://i.imgur.com/n5tjHFD.png',          });          razorpay.once('ready', function(response: any) {            console.log(response);

I cannot use "this" on a function

$
0
0

I am new to React Native. I want to create a simple counter button. I could not use "this", it gives error ('this' implicitly has type 'any' because it does not have a type annotation.). You can see my TabTwoScreen.tsx TypeScript code below. I searched other questions but i could not find what to do. Why this is not working and how can I correct it. Waiting for helps. Thanks a lot.

import * as React from 'react';import { StyleSheet, Button, Alert } from 'react-native';import EditScreenInfo from '../components/EditScreenInfo';import { Text, View } from '../components/Themed';export default function TabTwoScreen() {  const state={    counter: 0,  }  const but1 = () => {    this.setState({counter : this.state.counter + 1});  };  return (<View style={styles.container}><Text style={styles.title}>Counter:{state.counter}</Text><Button              title="Increment"              onPress={but1}              accessibilityLabel="increment"              color="blue"            /></View>  );}const styles = StyleSheet.create({  container: {    flex: 1,    alignItems: 'center',    justifyContent: 'center',  },  title: {    fontSize: 20,    fontWeight: 'bold',  },  separator: {    marginVertical: 30,    height: 1,    width: '80%',  },});

Error Message

Navigation is undefined in Drawer Content

$
0
0

I am currently trying to build a React Native project using typescript. My screens are configured as follows:

export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {    return (<NavigationContainer linking={LinkingConfiguration} theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}><DrawerNavigator /></NavigationContainer>    );}const Drawer = createDrawerNavigator<DrawerStackParamList>();function DrawerNavigator() {    const navigation = useNavigation<NavigationProps>();    return (<Drawer.Navigator drawerContent={() => <DrawerContent navigation={navigation} />}><Drawer.Screen name='Root' component={RootNavigator} /><Drawer.Screen name='ManageCities' component={ManageCities} /></Drawer.Navigator>    );}const Stack = createStackNavigator<RootStackParamList>();function RootNavigator() {    return (<Stack.Navigator><Stack.Screen name='Root' component={BottomTabNavigator} options={{ headerShown: true, headerLeft: () => <Header /> }} /><Stack.Screen name='NotFound' component={NotFoundScreen} options={{ title: 'Oops!', headerShown: true, headerLeft: () => <Header /> }} /></Stack.Navigator>    );}function Header() {    const navigation = useNavigation<NavigationProps>();    return <Ionicons size={30} name='ios-menu' color='white' onPress={() => navigation.toggleDrawer()} />;}

Drawer Content:

import React, { FunctionComponent } from 'react';import { View } from '../components/Themed';import { DrawerContentScrollView, DrawerItem } from '@react-navigation/drawer';import { NavigationProps } from '../types';type DrawerContentProps = {    navigation?: NavigationProps;};const DrawerContent: FunctionComponent<DrawerContentProps> = ({ navigation }) => {    const arr = ['city1', 'city2'];    return (<View style={{ flex: 1 }}><DrawerContentScrollView>                {arr.map(                    (value): JSX.Element => {                        return <DrawerItem key={value} label={value} onPress={() => console.log(value)} />;                    },                )}<DrawerItem label='Manage Cities' onPress={() => navigation!.navigate('ManageCities')} /></DrawerContentScrollView></View>    );};export default DrawerContent;

when I try to run the application, I get the following error:

Error: Couldn't find a navigation object. Is your component inside a screen in a navigator?This error is located at:    in DrawerNavigator    in EnsureSingleNavigator (created by ForwardRef(BaseNavigationContainer))    in ForwardRef(BaseNavigationContainer) (created by ForwardRef(NavigationContainer))    in ThemeProvider (created by ForwardRef(NavigationContainer))    in ForwardRef(NavigationContainer) (created by Navigation)    in Navigation (created by App)    in RNCSafeAreaProvider (created by SafeAreaProvider)    in SafeAreaProvider (created by App)    in App (created by ExpoRoot)    in ExpoRoot    in RCTView (created by View)    in View (created by AppContainer)    in DevAppContainer (created by AppContainer)    in RCTView (created by View)    in View (created by AppContainer)    in AppContainer

I also tried to use the useNavigation hook inside the drawer content as well but came across with the same error.

Actually my initial problem was that I couldn't figure out how to pass the navigation as a prop to DrawerNavigator. When using Javascript, you can pass props and it has navigation inside by default. However, in Typescript it complains that props are not defined and I couldn't figure out how to pass it initially.

Having issues setting a state to be immediately read by calendar strip on react native

$
0
0

I'm currently working with react-native-calendar-strip, which displays a horizontal/lineal/weekly calendar, whatever you call it, my idea is to click on a specific day and highlight it, but the way this component works, it separates the highlight style and the day style.

            const [isToday, setToday] = useState(false)<CalendarStrip              useIsoWeekday={false}              startingDate={fecha}              showMonth={false}              calendarHeaderContainerStyle={                styles.calendarHeaderContainerStyle              }              calendarColor={'#FFFFFF'}              style={styles.calendarStripContainer}              daySelectionAnimation={{                type: 'background',                highlightColor: '#F8F8F8',                duration: 300,              }}              onDateSelected={async (date) => {                updateState(date);                DataManager.FechaActual = Moment(date).format('YYYY-MM-DD');                await setFechaActual();              }}              dateNumberStyle={styles.calendarStripMediumText}              dateNameStyle={styles.calendarStripLowText}              highlightDateNumberStyle={[                styles.enabledDate,                {color: isToday ? '#212B42' : '#8E9CB4'},              ]}              highlightDateNameStyle={[                styles.enabledDate,                {color: isToday ? '#212B42' : '#8E9CB4'},              ]}              disabledDateNameStyle={styles.disabledDate}              disabledDateNumberStyle={styles.disabledDate}              customDatesStyles={customDatesStylesFunc}              disabledDateOpacity={1}              leftSelector={[]}              rightSelector={[]}              iconContainer={{flex: 0.1}}            />

my isToday const starts as a false, and whenever i click on a day, it compares the current day with the selected day on momentjs, if the result is true, the hook state will change, and the corresponding highlightDateNumberStyle will display the new style for that day.

the problem is, the hook state is always behind the color change, from what i know, this is due to state async nature, although this part of the code is not working, i have tried like 8 or 9 solutions and i really don't know if this is possible or not.

              onDateSelected={async (date) => {                updateState(date);                DataManager.FechaActual = Moment(date).format('YYYY-MM-DD');                await setFechaActual();              }}

and this is the function i call inside the onDateSelected.

              function updateState(date: any) {                var hoy = Moment(horaActual).isSame(Moment(date), 'days');                setToday(hoy);              }

Code Sharing between React and React Native

$
0
0

i am trying to find a good way to share codes between projects like Types and Redux Stores. The best 3 methods i've seen is:

  1. Npm package - creating a private package.
  • But if i wanted to change something in the npm package while developing, how would i do that?
  1. Git Submodules
  • I've seen that this way can have some side effects.
  1. Copy/Paste
  • The way i am doing now xD .. But really horrible way, cause i have to change the same stuff several times and can forget what i've changed..

How would u resolve this issue?

How to use DateTimePicker in react native with react-hook-form (Typescript)? [closed]

$
0
0

I'm making a form in react-native and I'm not able to include the react-datetime-picker library in that form when I click the subtmit button.

I tried to do this at the expo in a number of ways and I had no success.

Link to code.


How to verify Interface with Axios GET response using TypeScript

$
0
0

Data is coming back successfully from the API. This is my first time calling an API using TypeScript. The problem I am having is that I am not sure if my interface successfully verifies the API data or not.

const App = () => {  const [userData, setUserData] = useState<User[]>([])  console.log('User data: ', userData);  useEffect(() => {    axios      .get<User[]>('https://jsonplaceholder.typicode.com/users')      .then((response) => {        setUserData(response.data)      })      .catch(error => console.log(error.message))  }, [])  return ...};export default App;

Here is my interface

export interface User {  id: number,  name: string,  username: string,  email: string,  address: Address,  phone: string,  website: string,  company: Company,}export interface Address {  street: string,  suite: string,  city: string,  zipcode: string,  geo: Geolocation,}export interface Geolocation {  lat: string,  lng: string,}export interface Company {  name: string,  catchPhrase: string,  bs: string,}

How do i trigger an onPress event on a screen render in react native?

$
0
0

Basically what i'm trying to do is to trigger the onpress event whenever i get on this screen, i know how to do this on a non-hooks project, but i never encountered this case on hooks.

i got a calendar component that uses a onSelectedDate() to trigger something whenever you select a day in the calendar, what i need to do is to click on a specific day whenever i go to this screen, so that way it gets selected

do i need to use ref? or props? i don't know, need a example if possible

How to dispatch an AsyncThunk with the createAsyncThunk helper

$
0
0

I am currently trying to learn some typescript/redux/reactnative.

I think I have gotten the basic concepts of how redux handles state management. I am now however a bit stuck on trying to get asynchronous state management to work with the redux thunk middleware.

So far I have got this simple counter example:

Rootreducer.tsx

import { combineReducers } from "@reduxjs/toolkit";import { create } from "react-test-renderer";import { createStore, applyMiddleware } from "redux"import thunk, {ThunkMiddleware} from "redux-thunk";import { AppActions } from "../Util/Types";import counterReducer from "./CounterReducer"export const rootReducer = combineReducers({    counter: counterReducer})export type AppState = ReturnType<typeof rootReducer>const middleware = applyMiddleware(thunk as ThunkMiddleware<AppState, AppActions>)export const store = createStore(rootReducer, middleware)

CounterReducer.tsx:

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit"import { CounterState } from "../Util/Types"const initialState = { num : 0 } as CounterStatefunction delay(milliseconds: number, count: number): Promise<number> {    return new Promise<number>(resolve => {            setTimeout(() => {                resolve(count);            }, milliseconds);        });    }export const delayedIncrement =     createAsyncThunk ("delayedIncrement",        async(arg : number , thunkAPI) => {            const response = await delay(5000, 5)            return response        }    )const counterSlice = createSlice({    name: "counter",    initialState,    reducers: {        increment(state) {            state.num++        },        decrement(state) {            state.num--        },        incrementByAmount (state, action : PayloadAction<number>) {             state.num += action.payload        }    },    extraReducers : {        [delayedIncrement.fulfilled.type]: (state, action) => {            state.num += action.payload        },        [delayedIncrement.pending.type]: (state, action) => {            state.num        }    }})export const { increment, decrement, incrementByAmount } = counterSlice.actionsexport default counterSlice.reducer

Counter.tsx:

import { FC, useState } from "react";import  { Button, Text, View } from "react-native"import React from "react"import { connect, ConnectedProps, useDispatch } from "react-redux"import  { AppState } from "../Reducers/RootReducer" import { increment, decrement, incrementByAmount, delayedIncrement} from "../Reducers/CounterReducer";const mapState = (state : AppState) => ({    counter: state.counter.num})const mapDispatch = {    increment : () => ({ type: increment }),    decrement : () => ({ type : decrement }),    incrementByAmount : (value : number) => ({type: incrementByAmount, payload: 5})}const connector = connect(    mapState,    mapDispatch)type PropsFromRedux = ConnectedProps<typeof connector>interface CounterProps extends PropsFromRedux  {    a : string}const Counter : FC<CounterProps> = (props) => {    const dispatch = useDispatch     return (<View><Text>{props.a}</Text><Text>{props.counter.toString()}</Text><Button title="increment" onPress={props.increment}> </Button><Button title="decrement" onPress={props.decrement}> </Button><Button title="increment5" onPress= {  () => { props.incrementByAmount(5) }}> </Button><Button title="delayed" onPress= {  () => { dispatch (delayedIncrement(5)) }}> </Button></View>    )}export default connector(Counter)

When I try to dispatch the delayed increment as such:

<Button title="delayed" onPress= {  () => { dispatch (delayedIncrement(5)) }}> </Button>

I get the following error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:1. You might have mismatching versions of React and the renderer (such as React DOM)2. You might be breaking the Rules of Hooks3. You might have more than one copy of React in the same app

I have followed the documentation provided by redux fairly closely so I am not sure why I cannot get this to function? The error itself does not make much sense to me, but I am not that familiar with javascript in general.

Any pointers or help of any kind would be much appreciated.

Axios request getting network error on Expo

$
0
0

I have an expo mobile application running on an Android emulator and I'm trying to make a request to a local Node.js API. The request is through HTTPS protocol so I created self-signed certificates to be able to try the application.

Every time I try to make a request to the API Axios throws a Network error.

Network ErrorStack trace:  http://192.168.1.35:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:168381:25 in createError  http://192.168.1.35:19001/node_modules%5Cexpo%5CAppEntry.bundle?  platform=ios&dev=true&hot=false&minify=false:168285:26 in handleError  node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent  node_modules\react-native\Libraries\Network\XMLHttpRequest.js:600:10 in setReadyState  node_modules\react-native\Libraries\Network\XMLHttpRequest.js:395:6 in __didCompleteResponse  node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in   callFunctionReturnFlushedQueue  [native code]:null in callFunctionReturnFlushedQueue  ...

I tried the following:

  • Configuring the API IP on the mobile application as 10.0.2.2 as suggested in the GitHub issue and didn't work.
  • Testing the application without HTTPS, which works perfectly fine.
  • Testing my application on an iOS device, but it has the same behaviour as the Android emulator, it works with HTTP but it does not with HTTPS.
  • Accessing the HTTPS URL from the emulator's browser, which also works.

My HTTPS server is configured as follows:

const httpsServer = https.createServer(Certificate.getCertificate(), app);httpsServer.listen(Environment.PORT, "0.0.0.0");Logger.logInfo(`Listening on port ${Environment.PORT} under HTTPS protocol.`);

In order to create the self-signed certificates, I followed the Heroku guide

Why I got an Error: Can't display popup. Could not find view with tag XXX when using UIManager.showPopupMenu() method in React Native

$
0
0

Hello Everyone!

I want to show a native popup menu in Android using UIManager.showPopupMenu() method, but I got an Error Can't display the popup. Could not find view with tag XXX at the docs the first parameter of that method should be filled with a view tag number using the findNodeHandle() method.

It works fine if I am using a ref from <Pressable ref={handlePopupRef} /> but It doesn't work if I am using a ref from <View ref={handlePopupRef}></View>

I have no idea what's wrong with my code even when I am trying with ref callback it still doesn't work like <View ref={ref => handlePopupRef.current = ref}></View>

Code Samples

Icon.tsx

import React, {forwardRef, RefAttributes} from 'react';import {View, StyleProp, TextStyle} from 'react-native';import Icon from 'react-native-vector-icons/Feather';interface IconHelperProps {  name?: string;  size?: number;  color?: string;  style?: StyleProp<TextStyle>;}const IconHelper: React.ForwardRefExoticComponent<  IconHelperProps & RefAttributes<null>> = forwardRef((props, ref) => {  return (<View ref={ref}><Icon        name={props.name || 'help-circle'}        size={props.size || 24}        color={props.color || '#242424'}        style={[props.style]}      /></View>  );});export default IconHelper;

Button.tsx

import React, {useRef, useState} from 'react';import {  Pressable,  UIManager,  findNodeHandle,  StyleProp,  TextStyle,  ViewStyle,} from 'react-native';import Icon from './Icon';import Text from './Text';export interface ButtonHelperProps {  title?: string;  iconName?: string;  iconSize?: number;  iconColor?: string;  isDropdown?: boolean;  dropdownMenu?: string[];  style?: StyleProp<ViewStyle>;  textStyle?: StyleProp<TextStyle>;  onPress?: () => void;  onPressDropdownMenu?: (i: number | undefined) => void;}const Button: React.FC<ButtonHelperProps> = props => {  const {title, iconName, isDropdown} = props;  const [bgColor, setBgColor] = useState('transparent');  const handlePopupRef = useRef(null);  return (<Pressable      onPressIn={() => {        setBgColor('#E3E3E7');      }}      onPress={() => {        if (isDropdown) {          UIManager.showPopupMenu(            findNodeHandle(handlePopupRef.current),            props.dropdownMenu || ['Sample Menu'],            error => {              console.log(error);              console.error('Error Show Popup');            },            (e, i) => {              props.onPressDropdownMenu?.(i);            },          );        } else {          props.onPress?.();        }      }}      onPressOut={() => {        setBgColor('transparent');      }}      style={[        {          backgroundColor: bgColor,          borderRadius: title ? 8 : 0,          flexDirection: 'row',          alignItems: 'center',        },        props.style,      ]}>      // It's work fine when I am using a Ref from Pressable component      {/* {isDropdown && <Pressable ref={handlePopupRef}></Pressable>} */}      // But it doesn't work when I am using a Ref from View component      {iconName && (<Icon          name={iconName}          size={props.iconSize}          color={props.iconColor}          ref={ref => (handlePopupRef.current = ref)}        />      )}      {title && (<Text          size={14}          bold          style={[            {              paddingHorizontal: 24,              paddingVertical: 12,            },            props.textStyle,          ]}>          {title}</Text>      )}</Pressable>  );};export default Button;
Viewing all 6285 articles
Browse latest View live


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