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

How can I get the color information of a pixel in React Native?

$
0
0

I’m trying to implement color picking through the device camera in a project with expo-camera. In order to do this, I need to access the color information pertaining to a specific pixel on the screen, following user interaction.

What would be the best way to get that information?

My first thought was to snap a picture and use the tap coordinates to find the pixel I’m searching for in the image, and then extract the information from that image. To that end, I tried using the react-native-pixel-color library, but it seems it’s been abandoned. If this is indeed the best way of going about this, it’d be great to get some pointers as to how I can implement this functionality myself.


How do I Figure out React Navigation Return Types?

$
0
0

I'm used to strongly typed languages, but still very new to TypeScript and I'm having difficulty with understanding the types of different methods and such from other libraries. But I'm using the react-navigation library and I'm trying to figure out the types of a few things related to the Stack screen navigation.

Here's some example code from the official page:

import { createStackNavigator } from '@react-navigation/stack';const Stack = createStackNavigator();function MyStack() {  return (<Stack.Navigator><Stack.Screen name="Home" component={Home} /><Stack.Screen name="Notifications" component={Notifications} /><Stack.Screen name="Profile" component={Profile} /><Stack.Screen name="Settings" component={Settings} /></Stack.Navigator>  );}

If I dig into the creatStackNavigator() implementation, I see:

declare function StackNavigator({ initialRouteName, children, screenOptions, ...rest }: Props): JSX.Element;

So does this function return a JSX.Element? If so, why is it that when I try to use this type...:

const Stack: JSX.Element = createStackNavigator();

... that I get this error?:

Type 'TypedNavigator<Record<string, object | undefined>, StackNavigationState, StackNavigationOptions, StackNavigationEventMap, ({ initialRouteName, children, screenOptions, ...rest }: Props) => Element>' is missing the following properties from type 'Element': type, props, keyts(2739)

I'm interested in the specifics of this case in React Navigation, as well as general tips to better figure out the return types of functions, components, etc.

Edit:Specifically in my use case, I'm hoping to do something like the following, where I can have a function take the StackNavigator and use it to create screens so that I can have uniform options for all of my screens:

import React from 'react';import {View} from 'react-native';import {NavigationContainer} from '@react-navigation/native';import StackNavigator, TypedNavigator, {createStackNavigator} from '@react-navigation/stack';const DummyView = () => {    return <View/>;}// Instead of "any", what can I use as the type for stackNav?// Neither StackNavigator or TypedNavigator seemed to work, at least not with the imports I have for them.function createStackScreen (stackNav : any , name:string, component: React.ComponentType<any>) {    // I also think I'll have problems with the Screen    return (<stackNav.Screen        name={name}        component={component}        options={{        headerShown: false    }}/>);}const MyStack = createStackNavigator();const Index = () => {    return (<NavigationContainer><MyStack.Navigator>                {createStackScreen(MyStack, 'Main Screen', DummyView)}                {createStackScreen(MyStack, 'Secondary Screen', DummyView)}                {createStackScreen(MyStack, 'Tertiary Screen', DummyView)}</MyStack.Navigator></NavigationContainer>    );}export default Index;

getTheme() native base Type

$
0
0

I'm using a custom Native Base style theme as described in this link.

https://docs.nativebase.io/Customize.html#theaming-nb-headrefImports:

import material from './native-base-theme/variables/material';import getTheme from './native-base-theme/components';
return (<Suspense fallback="loading"><Provider store={store}><StyleProvider style={getTheme(material)}>

Inside getTheme(), on material, I get this TypeScript error:

Argument of type '{ platformStyle: string; platform: "ios" | "android"| "windows" | "macos" | "web"; headerStyle: string; iconStyle: string;contentStyle: string; expandedIconStyle: string; accordionBorderColor:string; ... 151 more ...; Inset: { ...; }; }' is not assignable toparameter of type '{ platformStyle: any; platform: "ios" | "android" |"windows" | "macos" | "web"; accordionBorderColor: string;accordionContentPadding: number; accordionIconFontSize: number;contentStyle: string; ... 180 more ...; Inset: { ...; }; }'. Type '{platformStyle: string; platform: "ios" | "android" | "windows" |"macos" | "web"; headerStyle: string; iconStyle: string; contentStyle:string; expandedIconStyle: string; accordionBorderColor: string; ...151 more ...; Inset: { ...; }; }' is missing the following propertiesfrom type '{ platformStyle: any; platform: "ios" | "android"

How do I get rid of this?

inside the native-base-themes folder, there's a material.js file that looks like this:

import color from 'color';import { Platform, Dimensions, PixelRatio } from 'react-native';import { PLATFORM } from './commonColor';const deviceHeight = Dimensions.get('window').height;const deviceWidth = Dimensions.get('window').width;const platform = Platform.OS;const platformStyle = PLATFORM.MATERIAL;const isIphoneX =  platform === PLATFORM.IOS &&  (deviceHeight === 812 ||    deviceWidth === 812 ||    deviceHeight === 896 ||    deviceWidth === 896);export default {  platformStyle,  platform,  // Android  androidRipple: true,  androidRippleColor: 'rgba(256, 256, 256, 0.3)',  androidRippleColorDark: 'rgba(0, 0, 0, 0.15)',  buttonUppercaseAndroidText: true,  // Button  buttonFontFamily: 'Roboto',  get buttonPrimaryBg() {    return this.brandPrimary;  },  get buttonTextSizeLarge() {    return this.fontSizeBase * 1.5;  },  // Header  toolbarBtnColor: '#fff',  toolbarDefaultBg: '#3F51B5',  toolbarHeight: 56,  toolbarSearchIconSize: 23,  toolbarInputColor: '#fff',  searchBarHeight: platform === PLATFORM.IOS ? 30 : 40,  searchBarInputHeight: platform === PLATFORM.IOS ? 40 : 50,  toolbarBtnTextColor: '#fff',  toolbarDefaultBorder: '#3F51B5',  iosStatusbar: 'light-content',  get statusBarColor() {    return color(this.toolbarDefaultBg)      .darken(0.2)      .hex();  },  get darkenHeader() {    return color(this.tabBgColor)      .darken(0.03)      .hex();  },  // Text  textColor: '#000',  inverseTextColor: '#fff',  noteFontSize: 14,  get defaultTextColor() {    return this.textColor;  },  // iPhoneX SafeArea  Inset: {    portrait: {      topInset: 24,      leftInset: 0,      rightInset: 0,      bottomInset: 34,    },    landscape: {      topInset: 0,      leftInset: 44,      rightInset: 44,      bottomInset: 21,    },  },};

How to cast inside .tsx file?

$
0
0

I wrote some code inside a .tsx file and I need to cast a variable but it doesn't work and I don't understand why.

That is my code :

let a : number = 2;let b : string = a as unknown as string;console.log("b type = "+typeof(b))

And that is the result :

b type = number

I think this is because I cast as unknown and then as string and I don't know why it's necessary but if I just write : let b : string = a as string;, I get the following error :

ERROR in App.tsx(59,22)  TS2352: Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

So does anyone know how to cast in .tsx file ? ( It's not possible to use <> for type casting otherwise it's considered as a React Element)

What can i do about it

$
0
0
    enter code hereimport React from 'react';import { StatusBar } from 'expo-status-bar';import { StyleSheet, Text, View, Dimensions } from 'react-native';import MapView, {Marker, Callout, PROVIDER_GOOGLE } from 'react-native-maps';//Styleimport mapMarker from './src/images/Map-marker.png';export default function App() {    return (<View style={styles.container}><MapView            provider={PROVIDER_GOOGLE}            style={styles.map}            initialRegion={{                latitude: -19.7641584,                longitude: -43.9347436,                latitudeDelta: 0.008,                longitudeDelta: 0.008,                }}><Marker                  icon={mapMarker}                  coordinate={{                    latitude: -19.7641584,                    longitude: -43.9347436,                  }}            /><Callout tooltip={true}><View style={styles.calloutContainer}><Text style={styles.calloutText}> Lar das meninas </Text></View></Callout>        </MapView></View>  );}const styles = StyleSheet.create({        container: {        flex: 1,  },    calloutContainer: {        width: 160,        height: 46,        paddingHorizontal: 16,        backgroundColor: 'rgba(255, 255, 255, 0.8)',        borderRadius: 16,        justifyContent: 'center',    },    calloutText: {},  map: {    width: Dimensions.get('window').width,    height: Dimensions.get('window').height,  }

});

That'S my entire code because I have no idea what's the problem.When I execute my application by [Expo-client-on-android] and returns this error...

I'm trying to make a marker in the map, and return info when clicked

https://drive.google.com/file/d/1Cep8ehUiehMeAfwesoMH5eNjrABztL3M/view?usp=sharing

React Native Typescript Typing for "Backwards" ScrollView

$
0
0

I've got a ScrollView which was working first as JavaScript and then also as TypeScript; this ScrollView uses the ref property to capture a reference of the ScrollView and then invoke one of its functions, scrollToEnd(). But I've recently beefed up my linting and I'm needing to figure out the proper way to get this reference property instance typed.

I started off with this:

import React from "react";import {ScrollView, StyleProp, ViewStyle} from "react-native";const standardStyle = {flex:1, backgroundColor:'black'};export default class ViewClass {    static produceBackwardScrollingView(customStyle : StyleProp<ViewStyle>, contents : any, horizontal : boolean) {        let scrollView : any;        return (<ScrollView                nestedScrollEnabled={true}                ref={ref => {                scrollView = ref            }}                onContentSizeChange={() => scrollView.scrollToEnd({animated: true})}                style={[standardStyle, customStyle]}                horizontal={horizontal}>{contents}</ScrollView>        );    }}

After a lot of wrestling with the types, I came up with this which I think is in the right direction, but I'm still getting TypeScript errors.

import React from "react";import {ScrollView, StyleProp, ViewStyle} from "react-native";const standardStyle = {flex:1, backgroundColor:'black'};export default class ViewClass {    static produceBackwardScrollingView(customStyle : StyleProp<ViewStyle>, contents : any, horizontal : boolean) {        let scrollView : React.RefObject<ScrollView> | ScrollView | null = React.createRef();        return (<ScrollView                nestedScrollEnabled={true}                ref={ref => {                    // below: scrollView maybe assigned "ScrollView" or "null"                    scrollView = ref                }}                // below: scrollView is possibly null                // also below: "Property 'scrollToEnd' does not exist on type 'ScrollView | RefObject<ScrollView>'."                onContentSizeChange={() => scrollView.scrollToEnd({animated: true})}                style={[standardStyle, customStyle]}                horizontal={horizontal}>{contents}</ScrollView>        );    }}

My scenario of course uses the ScrollView, so I guess if there's a better way to make the ScrollView start from the bottom that should probably fix my code in this instance. But I think this issue is generalizable in the sense that really my main problem is that I can't figure out what the type of my object reference needs to be and how to then invoke a function on it.

Note: I'm still new to React Native and TypeScript, so I may be slow to follow along.

TouchableOpacity onPress() only one button is working

$
0
0

Not sure why only the first onPress is working, other onPress no response..., just use the same way to wrap the function, but other onPress didn't respond at all

const ToMainScreen = () => {  navigation.navigate('Main')}const AskQuestion = () => {  setQuestionDisplay(true)  console.log("abc")}<TouchableOpacity onPress={ToMainScreen} ><Image    style={styles.homeIcon}    source={require('../image/homeIcon.png')}  /></TouchableOpacity><TouchableOpacity ><Image    style={styles.nextPageIcon}    source={require('../image/nextPage.png',)} /></TouchableOpacity><TouchableOpacity ><Image    style={styles.previousPageIcon}    source={require('../image/previousPage.png',)} /></TouchableOpacity><TouchableOpacity onPress={AskQuestion}><Image    style={styles.questionIcon}    source={require('../image/question.png',)} /></TouchableOpacity>    

React-Native : is it possible to cast a Video element into HTMLMediaElement?

$
0
0

Inside my React-Native code, I recover a Video element from reactxp-video package but then I need to give this element to a JS script but this script needs an HTMLMediaElement. I tried to cast my Video element into HTMLMediaElement but Typescript refused to cast a Video element into HTMLMediaElement.

I understand why it won't do it because : Type 'Video' is missing the following properties from type 'HTMLMediaElement': autoplay, buffered, controls, crossOrigin, and 276 more

Do you think it's possible to cast a Video element into HTMLMediaElement anyway with an another trick? (I was thinking about creating a VideoComponent which could extend React.Component and HTMLMediaElement but multiple inheritance is not allowed in Typescript).

Thank you,


RN FlatList with Typescript and Styled Components

$
0
0

SO community,

I can't figure out the correct type definition for an RN FlatList styled with Styled Components in Typescript

So I have type IProduct like that

interface IProduct {  id: string;  name: string;}

and I define the types for the FlatList like that

<FlatList  data={products}  renderItem={({ item }: { item: IProduct }) => (<SomeComponent item={item} />  )}  keyExtractor={(item: IProduct) => item.id}/>

everything works fine. Typescript does not complain but as soon as I want to style the FlatList like that

const StyledFlatList = styled.FlatList`  background-color: 'white';`;<StyledFlatList  data={products}  renderItem={({ item }: { item: IProduct }) => (<SomeComponent item={item} />  )}  keyExtractor={(item: IProduct) => item.id}/>

I get lots of Typescript errors

No overload matches this call.  Overload 2 of 2, '(props: StyledComponentPropsWithAs<typeof FlatList, DefaultTheme, {}, never>): ReactElement<StyledComponentPropsWithAs<typeof FlatList, DefaultTheme, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.    Type '({ item }: { item: IProduct; }) => JSX.Element' is not assignable to type 'ListRenderItem<unknown>'.  Overload 2 of 2, '(props: StyledComponentPropsWithAs<typeof FlatList, DefaultTheme, {}, never>): ReactElement<StyledComponentPropsWithAs<typeof FlatList, DefaultTheme, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.    Type '(item: IProduct) => string' is not assignable to type '(item: unknown, index: number) => string'.ts(2769)index.d.ts(4218, 5): The expected type comes from property 'keyExtractor' which is declared here on type 'IntrinsicAttributes & Pick<Pick<FlatListProps<unknown> & RefAttributes<FlatList<unknown>>, "ref" | "data" | "style" | "ItemSeparatorComponent" | ... 141 more ... | "key"> & Partial<...>, "ref" | ... 144 more ... | "key"> & { ...; } & { ...; } & { ...; }'index.d.ts(4218, 5): The expected type comes from property 'keyExtractor' which is declared here on type 'IntrinsicAttributes & Pick<Pick<FlatListProps<unknown> & RefAttributes<FlatList<unknown>>, "ref" | "data" | "style" | "ItemSeparatorComponent" | ... 141 more ... | "key"> & Partial<...>, "ref" | ... 144 more ... | "key"> & { ...; } & { ...; } & { ...; }'

Can someone tell me how to fix that error?

React Native TypeSrcript Function Returning JSX.Element Type

$
0
0

I've got a TypeScript function which returns a React Native View.

import React from "react";import JSX, {View} from "react-native";class DummyClass {    static getView() {        return (<View style={{flex: 1}}/>        );    }}export default DummyClass;

And I'm calling this function in this way:

import JSX from "react-native";import DummyClass from "./util/dummy";const DummyWrapper = () => {    return (DummyClass.getView());};export default DummyWrapper;

And when I run eslint, I get a warning.

5:5 warning Missing return type on function @typescript-eslint/explicit-module-boundary-types

So, I need to be returning something. JSX.Element seems reasonable enough, but that doesn't seem to be working. For one, when I try to return a JSX.Element, VSCode can't resolve it and pretends it's any instead. And moreover, it causes errors in other places that call the function.

So, doing this:static getView() : JSX.Element {and const DummyWrapper = () : JSX.Element => {

Results in the following error in DummyCaller:

5:5 error Unsafe return of an any typed value @typescript-eslint/no-unsafe-return

So now I'm not sure exactly what to do. I've tried a few other things, such as returning View, typeof View, React.Component (and typeof), and a few other things. I've also messed around with where JSX is being imported from. If I import from react, it seems to work even worse than if I import it from react-native. Also in my research, I see the most common problem is that one's React and React Native types are out of date, but as far as I can tell, I'm on the most up-to-date versions.

My packages.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","lint": "eslint -c .eslintrc.js --ext .tsx ."  },"dependencies": {"@dudigital/react-native-zoomable-view": "^1.0.15","@react-native-community/masked-view": "^0.1.10","@react-navigation/native": "^5.7.6","@react-navigation/stack": "^5.9.3","@types/react-native-vector-icons": "^6.4.6","change-case": "^4.1.1","expo": "~39.0.2","expo-status-bar": "~1.0.2","react": "16.13.1","react-dom": "16.13.1","react-native": "https://github.com/expo/react-native/archive/sdk-39.0.2.tar.gz","react-native-gesture-handler": "^1.8.0","react-native-paper": "^4.2.0","react-native-reanimated": "^1.13.1","react-native-safe-area-context": "^3.1.8","react-native-screens": "^2.11.0","react-native-tab-view": "^2.15.2","react-native-vector-icons": "^7.1.0","react-native-web": "^0.13.18"  },"devDependencies": {"@babel/core": "~7.9.0","@types/jest": "^26.0.15","@types/react": "^16.9.53","@types/react-dom": "^16.9.8","@types/react-native": "^0.63.27","@types/react-navigation": "^3.4.0","@types/react-redux": "^7.1.9","@types/react-test-renderer": "^16.9.3","@typescript-eslint/eslint-plugin": "^4.5.0","@typescript-eslint/parser": "^4.5.0","commonjs": "latest","eslint": "^7.11.0","eslint-plugin-jsdoc": "^30.7.3","eslint-plugin-prefer-arrow": "^1.2.2","eslint-plugin-react": "^7.21.5","react-native-typescript-transformer": "^1.2.13","requirejs": "latest","ts-jest": "^26.4.1","tslib": "^2.0.3","typescript": "^4.0.3"  },"private": true}

React Native Component Exception: undefined is not an object (evaluating'_this')

$
0
0

Iam working on face recognition app using react native 0.63. I am runing my project using react-native run-android. I get Component Exception undefined is not an object(evaluating '_this'). I am new to react native and I do not understand the meaning of this error.I am following the tutorial for this app but the tutorial is very old and thats why I am unable to update the code to latest version of react native. Here is the link of tutorialFace Recognition using react native. Please take a look and resolve my issue.

import React from 'react';import {StyleSheet,Text,View,Image} from 'react-native';import NativeModules, { ImagePickerManager } from 'react-native';import Button from './Button';import RNFetchBlob from 'react-native-fetch-blob';import _ from 'lodash';const Detector = props => {this.state = {    photo_style: {        position: 'relative',        width: 480,        height: 480    },    has_photo: false,    photo: null,    face_data: null};return (<View style={styles.container}><Image        style={this.state.photo_style}        source={this.state.photo}        resizeMode={"contain"}>        { this._renderFaceBoxes.call(this) }</Image><Button        title="Pick Photo"        onPress={()=>{this._pickImage.bind(this)}}        button_styles={styles.button}        button_text_styles={styles.button_text} />    { this._renderDetectFacesButton.call(this) }</View>);}  const _pickImage = () => {this.setState({    face_data: null});ImagePickerManager.showImagePicker(this.props.imagePickerOptions, (response) => {  if(response.error){    alert('Error getting the image. Please try again.');  }else{    let source = {uri: response.uri};    this.setState({      photo_style: {        position: 'relative',        width: response.width,        height: response.height      },      has_photo: true,      photo: source,      photo_data: response.data    });  }});}  const _renderDetectFacesButton = () => {    if(this.state.has_photo){        return  (<Button                title="Detect Faces"                onPress={()=>{this._detectFaces.bind(this)}}                button_styles={styles.button}                button_text_styles={styles.button_text} />        );    }  }  const _detectFaces = () => {RNFetchBlob.fetch('POST', 'https://api.projectoxford.ai/face/v1.0/detect?returnFaceId=true&returnFaceAttributes=age,gender', {'Accept': 'application/json','Content-Type': 'application/octet-stream','Ocp-Apim-Subscription-Key': this.props.apiKey}, this.state.photo_data).then((res) => {    return res.json();      }).then((json) => {    if(json.length){        this.setState({            face_data: json        });    }else{        alert("Sorry, I can't see any faces in there.");    }    return json;}).catch (function (error) {    console.log(error);    alert('Sorry, the request failed. Please try again.'+ JSON.stringify(error));});}  const _renderFaceBoxes = () => {if(this.state.face_data){    let views = _.map(this.state.face_data, (x) => {        let box = {            position: 'absolute',            top: x.faceRectangle.top,            left: x.faceRectangle.left        };        let style = {             width: x.faceRectangle.width,            height: x.faceRectangle.height,            borderWidth: 2,            borderColor: '#fff',        };        let attr = {            color: '#fff',        };        return (<View key={x.faceId} style={box}><View style={style}></View><Text style={attr}>{x.faceAttributes.gender}, {x.faceAttributes.age} y/o</Text></View>        );    });    return <View>{views}</View>} }const styles = StyleSheet.create({  container: {    flex: 1,    alignItems: 'center',    alignSelf: 'center',    backgroundColor: '#ccc'  },  button: {    margin: 10,    padding: 15,    backgroundColor: '#529ecc'  },  button_text: {    color: '#FFF',    fontSize: 20  }});export default Detector 

enter image description here

Npm install is giving Error in React-Native

$
0
0

I was trying to run npm install on a my project i deleted node modules to reinstall it again but I am getting a lot of errors on my terminal. All i did was npm install inside the supposed folder but was still getting errors. The error messages is below this message.Thanks

npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTCxxMethod.h'npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTCxxMethod.mm'npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTCxxModule.h'npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTCxxModule.mm'npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTCxxUtils.h'npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTCxxUtils.mm'npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTNativeModule.h'npm WARN tar ENOENT: no such file or directory, open 'C:\Users\APPname\node_modules\.staging\react-native-441da136\React\CxxModule\RCTNativeModule.mm'npm ERR! code E404npm ERR! 404 Not Found: preset@1.0.0npm ERR! A complete log of this run can be found in:npm ERR!     C:\Users\ABC\AppData\Roaming\npm-cache\_logs\2020-10-22T06_34_20_827Z-debug.log

npm-cache log file

13230 silly saveTree | | `-- postcss-value-parser@4.1.013230 silly saveTree | +-- hoist-non-react-statics@3.3.213230 silly saveTree | +-- shallowequal@1.1.013230 silly saveTree | `-- supports-color@5.5.013230 silly saveTree `-- validate.js@0.13.113231 verbose stack Error: 404 Not Found: preset@1.0.013231 verbose stack     at fetch.then.res (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\lib\fetchers\registry\fetch.js:42:19)13231 verbose stack     at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)13231 verbose stack     at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)13231 verbose stack     at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)13231 verbose stack     at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)13231 verbose stack     at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)13231 verbose stack     at Async._drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:133:16)13231 verbose stack     at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)13231 verbose stack     at Immediate.Async.drainQueues [as _onImmediate] (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)13231 verbose stack     at runCallback (timers.js:705:18)13231 verbose stack     at tryOnImmediate (timers.js:676:5)13231 verbose stack     at processImmediate (timers.js:658:5)13232 verbose cwd C:\Users\APPname13233 verbose Windows_NT 10.0.1836213234 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "i" "npm-install-global"13235 verbose node v10.15.313236 verbose npm  v6.4.113237 error code E40413238 error 404 Not Found: preset@1.0.013239 verbose exit [ 1, true ]

Typescript exported enum is undefined

$
0
0

I'm writing some typescript type definitions for an existing react native module.

What I've done so far:

  1. added path to my index.d.ts file in the react native module's package.json:
{"name": "react-native-my-module",// ..."main": "index.js","types": "typings/index.d.ts"}
  1. write my type definitions as follow:
import { EventSubscriptionVendor } from 'react-native';declare module "react-native-my-module" {    export enum MyValues {        ValueOne = 'one',        ValueTwo = 'two'    }    export interface SomeType<T> {        code: number,        description: string,        message: T    }    // ...}

The problem I have is that when I use this react native module in a react native test project, the type definitions seem to be used in my IDE but at runtime, the code below gives me undefined for the enum:

import Blabla, { MyValues, SomeType } from "react-native-my-module";// ...console.log('MyValues is =', MyValues); // gives  'MyValues is =, undefined'

Questions:

  • why is my enum undefined in the test project?

  • is there any other conf to add to the react-native module or the test project for typescript to work correctly?

How to use forwardRef with FunctionComponent in React Native using TypeScript

$
0
0

I've looked at many of the docs and examples but I still can't seem to quite understand how to use forwardRef with a functional component with TypeScript in React Native. Below is an example where I create a MyCustomComponent with a custom function that I try to call from the parent by creating a ref. However, since the ref is incorrectly defined and null, I obviously get an error message telling me that the function doesn't exist. Please help me understand how to properly use forwardRef in React Native. Thanks in advance!

interface MyCustomComponentProps {    title: string}const MyCustomComponent: React.FunctionComponent<MyCustomComponentProps> = React.forwardRef((props, ref) => {    const coolAlert = () => {        Alert.alert('Hey!', 'This was called from MyCustomComponent')    }    return (<View><Text>{props.title}</Text></View>    )})export default function App () {    const MyCustomComponentRef = useRef()    return (<SafeAreaView><MyCustomComponent ref={MyCustomComponentRef} title='Hello World' /><TouchableOpacity                onPress={() => {                    MyCustomComponentRef.coolAlert()                }}><Text>Click Me</Text></TouchableOpacity></SafeAreaView>    )}

React native ScrollView resets positon on setState

$
0
0

I have a ScrollView with buttons on it. I populate ScrollView dynamicaly. After I press on the buttons inside the ScrollView, I'm changing the state of the current selected index and the posiotion of ScrollView is resetting.

<ScrollView  ref={ref => {    this._scrollview = ref;  }}  style={styles.scrollview}  horizontal  showsHorizontalScrollIndicator={false}  snapToInterval={64}  snapToAlignment="start"  decelerationRate="fast"  contentContainerStyle={{ paddingRight: 8, paddingLeft: 8 }}>    {this._channels.map((item, index) =><TouchableWithoutFeedback        onLayout={event => {          const layout = event.nativeEvent.layout;          this._channelsPositions[index] = layout.x;        }}        key={item.userId}        onPress={() => this._changeIndex(index)}><Image          source={{ uri: videos[index][0].channelThumbnails.high.url }}          style={[styles.channelLogo, index == this.state.currentIndex ? { borderWidth: 2 } : {}]}        /></TouchableWithoutFeedback>    )}</ScrollView>_changeIndex = (newIndex: number) => {  const { currentIndex } = this.state;  if (newIndex == currentIndex) return;  this.setState({    currentIndex: newIndex  });  const newX = 16 + 48 * newIndex  this._scrollview.scrollTo({    x: 16 + 48 * newIndex,    y: 0,    animated: true  })}

And after I press the button I want ScrollView to move to x position of this button inside the ScrollView.Demo: https://streamable.com/gu1edy

Update: After i replace scrollview for Flatlist in header i think i understand why is it happening. But i still don't know how to fix it. So the behavior is same, i am getting scroll reset every time i press on the button/cell/item of scrollview/flatlist. How looks my flatlist with nested flatlist in header

\ |CHANNEL ICON 0|CHANNEL ICON 1|CHANNEL ICON 2| ... \     header with flatlist         \ FIRST ITEM IN FLATLIST WHICH CONTAINS VIDEO OF CHANNEL\  cell 0\ SECOND ITEM IN FLATLIST WHICH CONTAINS VIDEO OF CHANNEL\ cell 1

...

So after i klick on channel icon all main flatlist populates with new data so if i understand right the header rerendering and repopulates with new data too. So is there a possibility to update header with flatlist that way my scroll in header stays on it's position without resetting?


How to optimize App in ReactJS on re-renders

$
0
0

I have to optimize this App here, How can I implement or pass onDelete to Child so I don't have new function on each re-render? (I am not allowed to change the child component)

function App() {  const [names, setNames] = React.useState(["iamfirst", "methesecond"]);  const onDelete = useCallback( (index:number) => {    setNames((prev) => prev.filter((_, i) => i !== index));  }, []);  return (<div>      {names.map((name, index) => (<Child          key={index}          name={name}          onChange={onNameChange}          onDelete={()=>onDelete(index)}        />      ))}</div>  );}

Getting TS Error: Property 'user' does not exist on type 'IAuth | null'

$
0
0

I am using context for Auth in my simple typescript app.My context declaration is in the fileAuthProvider.tsx, which looks like:

import React, { createContext, useState } from 'react';import auth from '@react-native-firebase/auth';export interface IAuth {    user,    setUser,    login,    register,    logout}export const AuthContext = createContext<IAuth | null>(null);export const AuthProvider = ({ children }) => {    const [user, setUser] = useState(null);    return (<AuthContext.Provider            value={{                user: user,                setUser: setUser,                login: async (email, password) => {                    try {                        await auth().signInWithEmailAndPassword(email, password);                    } catch (e) {                        console.log(e);                    }                },                register: async (email, password) => {                    try {                        await auth().createUserWithEmailAndPassword(email, password);                    } catch (e) {                        console.log(e);                    }                },                logout: async () => {                    try {                        await auth().signOut();                    } catch (e) {                        console.log(e);                    }                },            }}>            {children}</AuthContext.Provider>    );};

This is how I am using it elsewhere:

  const { user, setUser } = useContext(AuthContext);

But Typescript throws 2 errors on this lien:

  1. Property 'user' does not exist on type 'IAuth | null'
  2. Property 'setUser' does not exist on type 'IAuth | null'

What can I do to bypass it?

Can't run jest tests on my react native application [React Native + TypeScript]

$
0
0

I'm trying to run tests on this project for the first time, but i having some problems with the modules, thats the error i'm having:

FAIL  src/components/text/index.test.tsx● Test suite failed to run    Cannot find module 'react' from 'src/components/text/index.test.tsx'> 1 | import React from 'react'        | ^      2 | import { render } from '@testing-library/react-native'      3 | import { ZzText } from './index'      4 |       at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:307:11)      at Object.<anonymous> (src/components/text/index.test.tsx:1:1)Test Suites: 2 failed, 2 totalTests:       0 totalSnapshots:   0 totalTime:        1.346 sRan all test suites.error Command failed with exit code 1.info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

And these are my jest config files:

package.json

"jest": {"moduleFileExtensions": ["js","jsx","ts","tsx"    ],"moduleDirectories": ["node_modules"    ]  },

babel.config.json

{"presets": ["@babel/preset-env", "@babel/preset-react"]}

tsconfig.json

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"isolatedModules": true,"jsx": "react","lib": ["es6"],"moduleResolution": "node","noEmit": true,"strict": true,"target": "esnext","declaration": true,"skipLibCheck": true  },"exclude": ["node_modules","babel.config.json","metro.config.js","jest.config.ts","example"  ],"include": ["src/**/*"]}

jest.config.ts

import type { Config } from '@jest/types'const config: Config.InitialOptions = {  preset: 'ts-jest',  testEnvironment: 'node',  transform: {'^.+\\.(ts|tsx|js|jsx)?$': 'babel-jest',  },  roots: ['<rootDir>/src'],}export default config

This the test i'm trying to run, i don't if i'm doing it right, i'm starting now with tests (it's a simple text component):

import React from 'react'import { render } from '@testing-library/react-native'import { ZzText } from './index'describe('', () => {  test('Should start with initial state', () => {    const { getByTestId } = render(<ZzText testID='firstTest' />)    const teste = getByTestId('firstTest')    console.log(teste)  })})

TypeScript issues when creating ref for React Native TextInput

$
0
0

I came across an issue when defining refs i.e.

inputRef = React.createRef(null)//...const someFunction () => { if (this.inputRef && this.inputRef.current) {   this.inputRef.current.focus() }}//...<TextInput ref={inputRef} />

When I access .focus() I get following error:

[ts] Property 'focus' does not exist on type 'never'. [2339]

Can I somehow tell createRef that this ref can be null or TextInput so it knows that .focus() may exist?

How can i convert node props in JS Code to TS Code?

$
0
0
    const SliderContainer = ({node, time}) => (<Container>            {node.map(program=>(<Slide                 key={program.id}                 id={program.id}                 title={program.title? trimText(program.title,8): trimText(program.name, 8)}                 overview={trimText(program.overview, 50)}                votes={program.vote_average}                backgroundImage={program.backdrop_path}                poster={program.poster_path}                />            ))}</Container>)

i wanna convert this JS Code to TS Code, so i tried

interface NodeProps {    node: Nodes    time: string}interface Nodes {    reactNode :{        id: number        title?: string        name?: string        overview: string        vote_average: number        backdrop_path: string        poster_path: string    }}const SliderContainer = ({node, time}: NodeProps) => (<Container><Swiper controlsEnabled={false} loop timeout={time}>            {node.map(program => (<Slide                 key={program.id}                 id={program.id}                 title={program.title? trimText(program.title,8): trimText(program.name, 8)}                 overview={trimText(program.overview, 50)}                votes={program.vote_average}                backgroundImage={program.backdrop_path}                poster={program.poster_path}                />            ))}</Swiper></Container>)

in the JS Code, node in Parameter is Proptypes.node. and contains id, title, vote...,etc. ( these things from movie API).and in result, the node.map() function is not work and i am searching many times how convert that code but i don't know.help me Please...

Viewing all 6213 articles
Browse latest View live


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