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

How to compare two objects value by iterating if both have same name in getDerivedStateFromProps?

$
0
0

The props coming from react is account and I'm keeping a copy of it as previousProps, before setting it to the state I need to compare each and every object and assign the value to state if both props object are different. However, both previous props and redux props are of same kind. Is there any way to iterate over it rather than writing one by one below.

static getDerivedStateFromProps(nextProps: Props, prevState: State) {    console.log("getDerivedStateFromProps");    Object.keys(nextProps.account).every((key) => {    // can i compare both keys with a loop.        if (nextProps.account.firstName !== prevState.previousProps.firstName) {            console.log("different");            return {                previousProps: nextProps,                userInfo: nextProps,                personalInfo: {                    first_name: nextProps.account.firstName,                },            };        }    });    if (nextProps.account.firstName !== prevState.previousProps.firstName) {        console.log("different");        return {            previousProps: nextProps,            userInfo: nextProps,            personalInfo: {                first_name: nextProps.account.firstName,            },        };    }    if (nextProps.account.lastName!== prevState.previousProps.lastName) {        console.log("different");        return {            previousProps: nextProps,            userInfo: nextProps,            personalInfo: {                last_name: nextProps.account.lastName,            },        };    }    return null;}

React Native Typescript Template doesn't work

$
0
0

I have created a new project of React Native with a typescript template using the official command react-native init MyApp --template typescript (a couple of times) and I can't see the changes I apply when I run the app.Looks like the hot reload its working on terms of refresh the screen but doesn't apply the changes. In the case I create the app without typescript all its working properly.

I don't get any error so I have no idea what I can do. Below its the package.json in case this help but its basically the autogenerated file from typescript template

{"name": "MyApp","version": "0.0.1","private": true,"scripts": {"start": "node node_modules/react-native/local-cli/cli.js start","test": "jest"  },"dependencies": {"react": "16.6.3","react-native": "0.58.4"  },"devDependencies": {"@types/jest": "^24.0.0","@types/react": "^16.8.2","@types/react-native": "^0.57.34","@types/react-test-renderer": "^16.8.0","babel-core": "7.0.0-bridge.0","babel-jest": "24.1.0","jest": "24.1.0","metro-react-native-babel-preset": "0.51.1","react-test-renderer": "16.6.3","ts-jest": "^23.10.5","typescript": "^3.3.3"  },"jest": {"preset": "react-native"  }}

tsconfig.json

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"isolatedModules": true,"jsx": "react","lib": ["es6"],"moduleResolution": "node","noEmit": true,"strict": true,"target": "esnext"  },"exclude": ["node_modules", "babel.config.js"]}

Any idea how I can get react-native working with typescript. Thanks!

how to use navigation.replace in TypeScript?

$
0
0

I am trying to use this in my code:

const navigation = useNavigation();navigation.replace('AllFriends')

But I keep getting an error that:

Property 'replace' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.

I also tried using this

const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()navigation.replace('route');

as suggested here: https://github.com/react-navigation/react-navigation/issues/8256

but this gives me an error on replace that expected 2 arguments but got only 1...

I am using "@react-navigation/native": "^5.5.1",

How to show alert popup only inside specific screen using react native?

$
0
0

In My case, I have implemented alert popup within a function and the function will call from componentDidMount(). Now the problem is the alert implemented inside the home screen but I am getting alert in other screen also. I want to show alert only when I am in home screen.

If user in other screen alert should not show.

My Code: (Home.tsx)

componentDidMount = async () => {    this.showAlert();}async showAlert() {Alert.alert(‘Hello’,          [            {              text: "ok",              onPress: () => {              },              style: 'cancel',            },            {              text: "goodbye",              onPress: () => {                  this.props.navigation.navigate(‘details);              },            },          ],          { cancelable: false },        );}

No overload match this call (Component React + Typescript)

$
0
0

In my placeholderTextColor the error of the title persist and do not find a solution

 import React from 'react';import { TextInputProps } from 'react-native';import { color } from 'react-native-reanimated';import { Container, TextInput, Icon } from './styles';interface InputProps extends TextInputProps {  name: string;  icon: string;}// todas as propriedades "rest" sao passadas para o TExt Input, no caso apenas o placeholderconst Input: React.FC<InputProps> = ({ name, icon, ...placeholder }) => (<Container><Icon name={icon} size={20} color="#666360" /><TextInput      keyboardAppearance="dark"      placeholderTextColor="#666360"      {...placeholder}    /></Container>);export default Input;

The error persists, if I remove spread operator the error is vanish, but it s not a solution

Full Error

(JSX attribute) placeholderTextColor?: string | typeof OpaqueColorValue | undefinedThe text color of the placeholder string

No overload matches this call.Overload 1 of 2, '(props: Pick<Pick<TextInputProps & RefAttributes, "ref" | "style" | "hitSlop" | "onLayout" | "pointerEvents" | "removeClippedSubviews" | ... 104 more ... | "showSoftInputOnFocus"> & Partial<...>, "ref" | ... 109 more ... | "showSoftInputOnFocus"> & { ...; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.Type 'ColorValue' is not assignable to type 'string | unique symbol | undefined'.Type 'unique symbol' is not assignable to type 'string | unique symbol | undefined'.Overload 2 of 2, '(props: StyledComponentPropsWithAs<typeof TextInput, DefaultTheme, {}, never>): ReactElement<StyledComponentPropsWithAs<typeof TextInput, DefaultTheme, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.Type 'ColorValue' is not assignable to type 'string | unique symbol | undefined'.Type 'unique symbol' is not assignable to type 'string | unique symbol | undefined'.ts(2769)index.d.ts(1626, 5): The expected type comes from property 'placeholderTextColor' which is declared here on type 'IntrinsicAttributes & Pick<Pick<TextInputProps & RefAttributes, "ref" | "style" | "hitSlop" | ... 107 more ... | "showSoftInputOnFocus"> & Partial<...>, "ref" | ... 109 more ... | "showSoftInputOnFocus"> & { ...; } & { ...; } & { ...; }'index.d.ts(1626, 5): The expected type comes from property 'placeholderTextColor' which is declared here on type 'IntrinsicAttributes & Pick<Pick<TextInputProps & RefAttributes, "ref" | "style" | "hitSlop" | ... 107 more ... | "showSoftInputOnFocus"> & Partial<...>, "ref" | ... 109 more ... | "showSoftInputOnFocus"> & { ...; } & { ...; } & { ...; }'

How to remove strings and special characters from string and show only numbers without comma using regex?

$
0
0

In My case I am using react native typescript, I want to get only numbers from group string without comma. How to get it using regex match or replace?

 taskname = TASK_XC0.0.0.0.89t_abc_test let task = taskname.match( /[0-9]+/g, ''); //0,0,0,0,89 

Actual output need to get 000089

Why do i get typescript unexpected token errors when compiling to web for expo, but not when compiling to android?

$
0
0

I've been trying to get a webrtc project made for android to work for the web.

The original project is written in react-native.

When i tried to use expo to compile to web, it gave me errors about unexpected token, not knowing what type was, and then what ?? was. These are things that are in the main code base, and they were failing in imported packages, ONLY when compiling to web.

I suppose I want to understand better why compiling the javascript for web, would be any different from compiling the javascript for android/ios... the loaders should be the same shouldn't they? At least for interpretting the javascript.

Typescript error when using useImperativeHandle alongside TextInput

$
0
0

I'm trying to convert ReactNative official example for useImperativeHandle with TypeScript

  • original:
function FancyInput(props, ref) {  const inputRef = useRef();  useImperativeHandle(ref, () => ({    focus: () => {      inputRef.current.focus();    }  }));  return <input ref={inputRef} ... />;}FancyInput = forwardRef(FancyInput);
  • with TypeScript:
import React, { ReactElement, Ref, useRef, useImperativeHandle, forwardRef } from "react";import { TextInput } from "react-native";interface FancyInputProps {  name: string;}const FancyInput = (props: FancyInputProps, ref: Ref<TextInput>): ReactElement => {  const inputRef = useRef<TextInput>(null);  useImperativeHandle(ref, () => ({    focus: () => {      inputRef.current.focus();    },  }));  return <input ref={inputRef} />;};export default forwardRef(FancyInput);

But focus is highlighted by my IDE with the following error message:

Type '{ focus: () => void; }' is missing the following properties fromtype 'TextInput': isFocused, clear, measure, measureInWindow, and 18more.

It's because TextInput have indeed other properties, but I want to only add one (focus), no rewrite all the others properties.

I have a feeling I'm not that far, any help will be very much appreciated!


How do I fix showing database with axios?

$
0
0

I have a todo list app on React/TypeScript/C#. I have made connection with database with axios. Adding or deleting items on both frontend and backend seems to work fine. But I can not see the text of my todo items, only checkboxes and delete buttons. Here is my code for getting items

const[todos, setTodos] = useState<ToDoData[]>([]);    useEffect(() => {        const fetchData = async () => {            const result = await                 axios.get("https://localhost:44354/api/ToDoItems")                  .then(result => setTodos(result.data));            console.log(data);        };        fetchData();    }, []);    

and adding data

 const addTodo = (title: string) => {        const newTodo: ToDoData = {            text: title,            id: Date.now(),            completed: false        }        setTodos(prev=>[newTodo, ...prev])        const result =        axios.post('https://localhost:44354/api/ToDoItems',            {                Content: title,                Completed: 0            }        )            .then((response) => { console.log(response) })            .catch(error => { console.log('the error has occured: '+ error) });    console.log(result)}

Also my database fields look like this:

[Required]        [Key]        public int Id { get; set; }        [Required]        [Column(TypeName = "nvarchar(40)")]        public string Content { get; set; }        [Required]        public int Completed { get; set; }

So how to fix data showing in frontend?

Thanks in advance!

Unable to nest stack navigator within a drawer navigator

$
0
0

I created a stack navigator which show be nested inside of a drawer navigation.My stack navigator code:

import * as React from "react";import { createStackNavigator } from "@react-navigation/stack";import HomeTabScreen from "../tabs";const Stack = createStackNavigator();const StackScreen = () => {<Stack.Navigator><Stack.Screen name="MainViewScreen" component={HomeTabScreen} /></Stack.Navigator>;};export default StackScreen;

and my drawer component which will be the root is as follows

import React from "react";import { createDrawerNavigator } from "@react-navigation/drawer";import SettingScreen from "../../screens/settings";import StackScreen from "../stack/index";const Drawer = createDrawerNavigator();const AppDrawerNavigation = () => {  return (<Drawer.Navigator><Drawer.Screen        name="Home"        component={StackScreen}        options={{          title: "home",        }}      /><Drawer.Screen name="Settings" component={SettingScreen} /></Drawer.Navigator>  );};export default AppDrawerNavigation;

But I get this message typescript and won't compile

Type '() => void' is not assignable to type 'ComponentClass<any, any> | FunctionComponent<any> | undefined'.  Type '() => void' is not assignable to type 'FunctionComponent<any>'.    Type 'void' is not assignable to type 'ReactElement<any, any> | null'.ts(2322)types.d.ts(290, 5): The expected type comes from property 'component' which is declared here on type '(IntrinsicAttributes & { name: "Home"; options?: DrawerNavigationOptions | ((props: { route: Route<"Home", object | [![enter image description here][1]][1]undefined>; navigation: any; }) => DrawerNavigationOptions) | undefined; listeners?: Partial<...> | ... 1 more ... | undefined; initialParams?: object | undefined; } & { ...; }) | (IntrinsicAttributes ...'

Please refer to the image to see where the error originates.Test Image

React Native header bar

$
0
0

How can I configure the Android header bar background color similar to the ios with react native?

enter image description here

Thanks

Adding type for useRef on ScrollView react-native

$
0
0

Looking to create a ref to a ScrollView component like so: const ref = useRef<ScrollView>(null); (or something to this effect) essentially I need access to the flashScrollIndicators method like this:

<ScrollView  ref={ref}  onContentSizeChange={() => ref?.current?.flashScrollIndicators()}>  {children}</ScrollView>

The code does work in my app however typescripts definitions for ScrollView doesn't seem to include flashScrollIndicators?I'm getting Property 'flashScrollIndicators' does not exist on type 'ScrollView'.ts(2339) looking through the types I can see SectionList and Flatlist so unsure if this is an bug with the definitions or just me not using it properly.

matter.js circular area with bodies inside

$
0
0

I'm trying to find a way to build a circular area with borders and put rigid bodies inside

Didn't find an easy way to make it.

There's one example of a terrain built from an SVG:

if (typeof $ !== 'undefined') {        $.get('./svg/terrain.svg').done(function(data) {            var vertexSets = [];            $(data).find('path').each(function(i, path) {                vertexSets.push(Svg.pathToVertices(path, 30));            });            terrain = Bodies.fromVertices(400, 350, vertexSets, {                isStatic: true,                render: {                    fillStyle: '#2e2b44',                    strokeStyle: '#2e2b44',                    lineWidth: 1                }            }, true);            World.add(world, terrain);        });    }

Am I right that I will have to use the same logic and add a lot of bodies (an approximation of PI) to build a circular area?

How to use react-native-webview-leaflet?

$
0
0

I'm devolopping an app using React Native and Expo. And I want to integrate react-native-webview-leaflet. But when I want to use the tag WebViewLeaflet so that I can be able to use WMS with GeoServer, it underlines the tag then shows this error when I hover the cursor.

JSX element type 'WebViewLeaflet' does not have any construct or call signatures.ts(2604)

Peek Problem No quick fixes available.

And when I try to run I get this errors

Some times this one

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in The fact, I have followed the step of installation but nothing work fine for me.

and other time this one

WebView has been removed from React Native. It can now be installed and imported from 'react-native-webview' instead of 'react-native'. See https://github.com/react-native-community/react-native-webview

Here is my code

import React, {Component} from 'react';import WebViewLeaflet from 'react-native-webview-leaflet';import { View } from 'react-native'; export default class Map extends Component{    render(){      return (<View><WebViewLeaflet/></View>      )    }}

Package.json

{"main": "node_modules/expo/AppEntry.js","scripts": {"start": "expo start","android": "expo start --android","ios": "expo start --ios","web": "expo start --web","eject": "expo eject"  },"dependencies": {"@react-native-community/masked-view": "^0.1.6","expo": "~36.0.0","expo-asset": "^8.0.0","expo-file-system": "^8.0.0","expo-font": "^8.0.0","leaflet": "^1.3.4","react": "~16.9.0","react-dom": "~16.9.0","react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz","react-native-dynamic-vector-icons": "^0.2.1","react-native-gesture-handler": "^1.5.3","react-native-maps": "^0.26.1","react-native-paper": "^2.2.2","react-native-reanimated": "^1.5.0","react-native-safe-area-context": "^0.6.2","react-native-screens": "^2.0.0-alpha.12","react-native-vector-icons": "^6.6.0","react-native-web": "~0.11.7","react-native-webview-leaflet": "^4.3.4","react-navigation": "^4.0.10","react-navigation-drawer": "^2.3.3","react-navigation-material-bottom-tabs": "^2.1.5","react-navigation-stack": "^2.0.15","react-navigation-tabs": "^2.7.0"  },"devDependencies": {"@types/react": "~16.9.0","@types/react-native": "~0.60.23","@babel/core": "^7.0.0","babel-preset-expo": "~8.0.0","typescript": "~3.6.3"  },"private": true}

ReactNative:Can't perform a React state update on an unmounted component

$
0
0

bug

11:48Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.bug error

intent

I want to use the modal-box to play the video by clicking on the video-image list. So I wrote openVideoFunc to switch video-URL and show/hide modal-box.

code

// Require local imgconst image1 = require('./assets/img/1.jpg')const image2 = require('./assets/img/2.jpg')// Require local videoconst video1 = require('./assets/video/1.mp4')const video2 = require('./assets/video/2.mp4')// array object for img/videoconst videoRes = [{"videoId": 1,"videoUrl": video1,"posterUrl": image1,"title": "test1","describe": "test1......"},...]export default function App() {  const [visible, setVisible] = React.useState(false);  const [videoUrl, setVideoUrl] = React.useState(null)// Video Poster List  const listItems = videoRes.map(item =><TouchableOpacity onPress={() => openVideoFunc(item)} key={item.videoId}><Layout><Image source={item.posterUrl} /></Layout></TouchableOpacity>  )//open video func  const openVideoFunc = (item) => {    setVideoUrl(item.videoUrl) //Switch video url    setVisible(true) //open modal  }  return (<Layout>        {listItems}<Modal visible={visible}><Button onPress={() => setVisible(false)} /> //close modalbox           <VideoPlayer source: videoUrl /> //videoplayer</Modal></Layout>  );}

How can I call a C++ method from react native?

$
0
0

I want to add a C++ file and call its methods from react-native repository.I have already tried some of the answers which says to install ffi-napi but that is not working. There are some specific tools requirement for this dependency.

So is there a way I can call the C++ methods without installing any dependency?

How to write type definitions for firebase objects in react?

$
0
0

I am trying to integrate firebase with react-native(expo). I followed the firebase documentation found here. The documentation was quite straight-forward and works as intended, but since the document is in JS and I am coding in typescript, I am receiving quite a few errors on my linter.

So few points about the code below

  1. i have defined the SuccessfullyAuthenticatedUser because the type of parameter changes when I call the method onSignIn(result) within signInWithGooglAsync
  2. in onSignIn function i am recieving a value from firebase. The value received comes with type definitions, but value.additionalUserInfo.profile is defined as Object | null | undefined, therefore i am unable to access the values inside profile Object without explicitly defining profile as any. ESlint is kinda mad at that.
  3. In the isUserEqual function googleUser object has no method called getUserProfile().getUserId(). I tried to explicitly define type for that but I do not know how to define types for functions(classes?) which have functions of their own

I am quite sure that I am doing a lot of things wrong, and chasing down a rabbit hole. So someone please suggest me how to implement this in a better way or tell me how I resolve point 2 and 3.

interface SuccessfullyAuthenticatedUser {  ...  type: "success";  getBasicProfile?: any;}const signInWithGoogleAsync = async () => {    try {      const result = await Google.logInAsync({...});      if (result.type === "success") {        onSignIn(result);         ...      }      ...    } catch (e) {      ...    }  };const onSignIn = (googleUser: SuccessfullyAuthenticatedUser) => {    ....    ....        firebase.auth().signInWithCredential(credential).then((value) => {            const profile: any = value.additionalUserInfo?.profile;            firebase.database().ref(...).set({              ...              first_name: profile.given_name,            });          })      ...  });};const isUserEqual = (    googleUser: SuccessfullyAuthenticatedUser,    firebaseUser: firebase.User | null,  ) => {    if (firebaseUser) {      if (providerData[i]!.uid === googleUser.getBasicProfile().getId()){            ...      }    return false;  };  

react-native run-ios is taking .e2e.ts file instead of .ts file

$
0
0

I'm dealing with a curious issues : I'm using detox for e2e testing, and in order to mock my API, I'm using two files:

  • api-service.ts : The API Service for my app
  • api-service.e2e.ts : The API Mock for testing

With detox, all is working : RN_SRC_EXT=e2e.ts detox build -c ios && detox test -c ios and my tests perfectly works.

But when I start the app with react-native run-ios it's the mock file that is used instead of the normal file.

While debugging I've trying multiple way:

  • Print a big console.log "GOOD FILE" in the "normal file" and "WRONG FILE" in the mock file (surprise, it's WRONG FILE which is logged each time)
  • Explicitly run RN_SRC_EXT=anythingButNote2eExt.ts react-native run-ios
  • Remove ios/build folder ❌
  • Remove api-service.e2e.ts✅ (oh it's work here)
  • Restore api-service.e2e.ts after removing it ❌ (😭)

More curious when I run RN_SRC_EXT=qwerty.ts detox build -c ios && detox test -c ios the test fail and so take the right api-service.ts file...

I've also double check: the file api-service.e2e.ts isn't imported from any file of the whole project, and the env variable RN_SRC_EXT isn't globally set.

So I'm completely lost and I can't find any problem of this kind on the internet. Your help will be extremely appreciated.

Thanks.

PS : as you see with the file extension, I'm using typescript but I don't think that's the cause of the problem.

EDIT : More details, my metro.config.js look like :

const defaultSourceExts = require("metro-config/src/defaults/defaults").sourceExts;console.log("Resolver EXT", process.env.RN_SRC_EXT);module.exports = {  transformer: {    getTransformOptions: async () => ({      transform: {        experimentalImportSupport: false,        inlineRequires: false,      },    }),  },  resolver: {    sourceExts: process.env.RN_SRC_EXT      ? process.env.RN_SRC_EXT.split(",").concat(defaultSourceExts)      : defaultSourceExts,  },};

And the console.log("Resolver EXT", process.env.RN_SRC_EXT); Always log e2e.ts even if I set this variable with other value...

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);

Expo React Native with Type Script written package

$
0
0

Trying to use Sync-Storage ( it's written in type script ) and I am using a clean install of expo init project_name

I trying to get React Native Web running, and I'm not sure how to fix this error or what to install to support. Anyone share some light please?

/Users/myname/Work/ReactNative/testapp/node_modules/sync-storage/src/index.js 5:5Module parse failed: Unexpected token (5:5)You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders| import handleError from './helpers/handleError';| > type KeyType = string;| | class SyncStorage {

PS: My project is in JAVASCRIPT

PS2: I can use this package with no problem if i use use manual react native installation

Viewing all 6213 articles
Browse latest View live


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