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

React is not defined for my own React Native component library

$
0
0

I have made simple React Native component library for testing:

import React from "react";import { Text } from "react-native";const TestComponent = () => <Text>Test test</Text>;export default TestComponent;

The project link is here: https://github.com/kdong007/test-component

After I have installed this in my main project using "yarn add ../test-component" and added into UI, I got "React is not defined" error

enter image description here

What is with my package setting?


Argument of type '"openURL"' is not assignable to parameter of type 'never' using Jest

$
0
0

I am beginner in Jest and these are classes defined.APIService class is not exported; only openURL function is defined.

APIService.ts

    export const openURL = async (openURL : string) => {    await Linking.openURL(openURL );};

RegistrationPage.tsx

import{openURL} from '../APIService';

RegistrationPage.test.ts

test('should call function openURL with empty value', async () => {const url = '';const mockOpenURL = jest.fn();mockOpenURL .mockImplementation(() => Promise.resolve(''));const openURLSpy = jest.spyOn(openURL, 'openURL');const mockURL = await openURL(url);expect(mockOpenURL).toBeCalled();expect(mockURL).toEqual(url);expect(mockOpenURL).toHaveBeenCalledWith(url);openURLSpy.mockRestore();

});

After writing this function as per my understating may be it has loopholes not having properly mocked or spyedrunning it causing an error for Argument of type '"openURL"' is not assignable to parameter of type 'never' using Jest

suggestions to improve this testcase will be helpful.

React native with typescript passing useState as props

$
0
0

I have responsive.tsx file and I want to take an useState hook as props that contains orientation mode for app from app.tsx. I have an issue with types.

Argument of type 'Dispatch<SetStateAction>' is not assignable to parameter of type 'Props'. Property 'setOrientation' is missing in type 'Dispatch<SetStateAction>' but required in type 'Props

 //in responsive.tsxtype OrientationProp = {    orientation:string}type Dispatcher<S> = Dispatch<SetStateAction<S>>;type Props = {    setOrientation : Dispatcher<any>}const listenOrientationChange = ({ setOrientation  }:Props) => {  Dimensions.addEventListener("change", (newDimensions) => {    // Retrieve and save new dimensions    screenWidth = newDimensions.window.width;    screenHeight = newDimensions.window.height;    // Trigger screen's rerender with a state update of the orientation variable  });  let orientation:OrientationProp = {    orientation: screenWidth < screenHeight ? "portrait" : "landscape",  };  setOrientation(orientation);};//in app.tsx    const [orientation,setOrientation] = useState(null);      useEffect(() => {        listenOrientationChange(setOrientation) // the error is here //Argument of type 'Dispatch<SetStateAction<null>>' is not assignable to parameter of type 'Props'. Property 'setOrientation' is missing in type 'Dispatch<SetStateAction<null>>' but required in type 'Props'      },[])

Can I extend a component's constructor with additional arguments?

$
0
0

Consider a sample component:

enum PET_TYPE {  CAT = 'cat',  DOG = 'dog',  OTHER = 'other',}interface Props {  type: PET_TYPE}function Pet(props: Props) {  switch (props.type) {    case PET_TYPE.CAT: return (<>MEOW!</>);    case PET_TYPE.DOG: return (<>WOFF!</>);    default:           return (<>HELLO</>);  }}Pet.PET_TYPE = PET_TYPE;export default Pet;

That will be used like this:

import Pet from "./Pet";<Pet type={Pet.PET_TYPE.CAT} />

Do you think that the addition of PET_TYPE as an attribute of the component constructor is something that can be done or should it be avoided?

How to use useRef with Typescript/Formik?

$
0
0

I am passing a ref property into my custom FieldInput that I use for Formik validation of my form. However, it gives a few Typescript errors. For instance, in my function:

    const handleSubmitForm = (    values: FormValues,    helpers: FormikHelpers<FormValues>,  ) => {    setShowFlatList(true);    Keyboard.dismiss();    helpers.resetForm();    if (fieldRef && fieldRef.current){          fieldRef.current.blur();}    helpers.resetForm();  };

I get an error on fieldRef.current that Object is possibly 'undefined'.. I thought adding the if condition would fix it but it didn't. Also, when I submit the form, I get a warning that

Warning: An unhandled error was caught from submitForm()Error: "fieldRef.current.blur is not a function. (In 'fieldRef.current.blur()', 'fieldRef.current.blur' is undefined)" in handleSubmitForm 

Similarly, in my custom FieldInput component where I use ref={fieldRef}, I get an error that:

Type '{ ref: MutableRefObject<undefined>; setFieldTouched: (field: string, isTouched?: boolean | undefined, shouldValidate?: boolean | undefined) => void; handleChange: { ...; }; ... 4 more ...; placeholderText: string; }' is not assignable to type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.  Property 'ref' does not exist on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.ts(2322)

How can I fix these?

Here's a codesandbox:

https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

Successfully uploaded image to Cloudinary from React Native does not return URL

$
0
0

I'm trying to upload image from React Native app to Cloudinary.The image appears on Dashboard, but I don't get secure_url.

Here is my code:

  async uploadImage(photo: ImagePickerResponse, id: string): Promise<string> {    return new Promise<string>(async (resolve, reject) => {      const uploadPreset = 'bbbbbb';      const cloudName = 'aaaaa';      const body = new FormData();      const uri: string =        Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', '');      const type = photo.type;      const name = `eMia${id}.jpeg`;      const file = {uri, type, name};      body.append('file', file);      body.append('upload_preset', uploadPreset);      body.append('cloud_name', cloudName);      const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;      fetch(url, {method: 'POST', body})        .then((res) => {          // I don't have Body here so i don't have the image url :(          console.log(res);          res.json();        })        .then((json) => {          console.log(json);          const url = json.secure_url;          console.log(url);          resolve(url);        })        .catch((err) => {          reject(err);        });    });  }

Response:

enter image description here

Overriding method in typescript?

$
0
0
export class Person extends Component<...>{    getName(){        console.log('Person')    }    render(){        this.getName()    }   }export class Programmer extends Person{    getName(){        console.log('Programmer')    }}

Calling new Programmer().render() what should be logged? I see Person in my code. Why is that? Any resources would be helpful.

React Native Navigation Prop Not passing parameters correctly

$
0
0

In my React Native application, I have the following routes in my app.js set up:

export default class App extends Component {  render() {    return (<NavigationContainer><Stack.Navigator initialRouteName="Home"><Stack.Screen          name="Home"          component={ItemListing}          /><Stack.Screen          name="Details"          component={ItemImageDetails}          /></Stack.Navigator></NavigationContainer>    )  }}

I have a ItemListing component that has multiple ItemImage components that on press should navigate to the Details page which is the ItemImageDetails component by passing in a unique id. These are written in Typescript.

The ItemListing passes the navigation prop to the ItemImage as such:

import { NavigationScreenProp } from 'react-navigation'...interface ItemListingProps {  navigation: NavigationScreenProp<any,any>}export default class ItemListing extends Component<ItemListingProps,ItemListingState> {  constructor (props: ItemListingProps) {    super(props)    this.state = {      results: [],      searchTerm: ""    }  }  ...  render() {    return (<><View>              {this.state.results.map((result,index) =><ItemImage                  navigation={this.props.navigation}                  imageMetadata={result.data[0]}                  imageUrl={result.links[0].href}                  key={index}                />              )}</View></>    )  }}

The ItemImage is written as:

import { NavigationScreenProp } from 'react-navigation'...interface ItemImageProps {  navigation: NavigationScreenProp<any,any>  imageMetadata: ImageMetadata  imageUrl: string}export default class ItemImage extends Component<ItemImageProps,{}> {  constructor (props: ItemImageProps) {    super(props)  }  render() {    return (<><TouchableOpacity          onPress={() =>             this.props.navigation.navigate('Details', {               id: this.props.imageMetadata.id            })          }></TouchableOpacity></>    )  }}

The ItemImageDetails component is as below:

interface ItemImageDetailsProps {  id: string}export default class ItemImageDetails extends Component<ItemImageDetailsProps, {}> {  constructor (props: ItemImageDetailsProps) {    super(props)  }  ...  render() {    return (<><Text>THIS IS THE DETAILS PAGE</Text><Text>{this.props.id}</Text>      ...</>    )  }}

However, the id in the props of the ItemImageDetails is shown as 'undefined' in a console.log. There are no errors and the project builds correctly. The Details page is successfully navigated to and the id is correct in the ItemImage component, it just seems to be passing incorrectly within the navigation prop


Render resolved or rejected value of Promise in ReactJS

$
0
0

So, I've got this function fetchData() that returns a promise which is either rejected or resolved. How can i Call fetchData and if promise resolves, render it on the page, Display loading text while promise is not fulfilled yet and If promise is rejected, display custom text on page?how can i do that?

function fetchData() {    return new Promise((resolve, reject) => {        const time = Math.random() * 1000;        setTimeout(() => {            if (Math.random() > 0.5) {                resolve(`resolved`);            } else {                reject(new Error("error"));            }        }, time);    });}

How to access and change child's state from Parent component

$
0
0

You are given uncontrollable child component.Parent component stores number of counters and renders that amount of child components. It has two buttons Add counter and Increment all counters.

  1. You are not allowed to edit child component.

  2. ImplementincrementCounters so that it increments counters of all childcomponents that are rendered.

    incrementCounters = () => {// TODO: implement};


export class ChildCounter extends React.Component{    state = {        counter: 0    };    increment = () => {        this.setState(({ counter }) => ({            counter: counter + 1        }));    };    render() {        return (<div>                Counter: {this.state.counter}<button onClick={this.increment}>+</button></div>        );    }}

import {ChildCounter} from "./Child";class App extends React.Component {    state = {counters:1}    addCounter = () => {     let counterRn = this.state.counters + 1;     this.setState({counters:counterRn})    };   incrementAll = () => {   }   render() {   return (<div>                { new Array(this.state.counters).fill(0).map((_, index) => {                    return <ChildCounter key={index} />;                })                }<br/><button style={{marginRight:10}} onClick={this.addCounter}>Add Counter</button><button onClick={this.incrementAll}>Increment all counters</button></div>   )   }}

Resolve promise after callback it's executed

$
0
0

I have the following code on which I am trying to block the execution of the method _saveAddress multiple time, so I made a promise for this method.

  const [pressEventDisabled, setPressEventDisabled] = useState(false);<TouchableOpacity        style={style.button_container}        activeOpacity={1}        disabled={pressEventDisabled}        onPress={async () => {          setPressEventDisabled(true);          await _saveAddress();          setPressEventDisabled(false);        }}>

The problem is that I want to resolve the promise after the callback method it's executed. It's there any way to wait for the dispatch function to execute or to resolve the promise inside the callback method?

This is the method for saving the address:

    const _saveAddress = () =>        new Promise(async (resolve) => {          var valid = _validate();          if (valid) {            const address = createAddressJson();            if (addressId) {              var addressIdProperty = {id: addressId};              const newAddress = Object.assign(addressIdProperty, address);              dispatch(editAddress(newAddress, _onAddressSaveEditCallback));            } else {              dispatch(addAddress(address, _onAddressSaveEditCallback));            }          } else {            //notify            notifyMessage(strings.fill_required_inputs_validation);            resolve();          }        });

This is the callback method:

      const _onAddressSaveEditCallback = async (        success: boolean,        apiValidations: any,        address?: Address,      ) => {        if (success) {          if (typeof callback == 'function') {            callback(address);          }          await Navigation.pop(componentId);        } else {          setDataValidations(apiValidations);        }      };

Cannot create a React Native + TypeScript app by following official directions

$
0
0

With the following context:

$ node -vv14.8.0$ npm -v6.14.7$ yarn -v1.21.1$ tsc -vVersion 4.0.2

and following the instructions here: https://reactnative.dev/docs/typescript

I tried to create a React Native+TypeScript app with the following command:

$ npx react-native init app --template react-native-template-typescript

but got the following file structure:

enter image description here

where you can see I don't get any .tsx file (I was actually expecting that) even when I used the correspnding TypeScript template on the creation command above.

Later on they have the section: Adding TypeScript to an Existing Project, but I didn't do the the steps there because what I want to do is not exactly add TypeScript to an existing React Native project, but just creating a React Native project with TypeScript from the beginning.

Is there anything wrong I'm doing here?

Thanks for you attention.

global.HermesInternal - Property 'HermesInternal' does not exist on type 'Global & typeof globalThis'

$
0
0

I have the code below, auto generated with:

$ react-native init RepeatAloud

App.tsx

/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */import React from 'react';import {  SafeAreaView,  StyleSheet,  ScrollView,  View,  Text,  StatusBar,} from 'react-native';import {  Header,  LearnMoreLinks,  Colors,  DebugInstructions,  ReloadInstructions,} from 'react-native/Libraries/NewAppScreen';const App: () => React.ReactNode = () => {  return (<><StatusBar barStyle="dark-content" /><SafeAreaView><ScrollView          contentInsetAdjustmentBehavior="automatic"          style={styles.scrollView}><Header />          {global.HermesInternal == null ? null : (<View style={styles.engine}><Text style={styles.footer}>Engine: Hermes</Text></View>          )}<View style={styles.body}><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>Step One</Text><Text style={styles.sectionDescription}>                Edit <Text style={styles.highlight}>App.js</Text> to change this                screen and then come back to see your edits.</Text></View><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>See Your Changes</Text><Text style={styles.sectionDescription}><ReloadInstructions /></Text></View><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>Debug</Text><Text style={styles.sectionDescription}><DebugInstructions /></Text></View><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>Learn More</Text><Text style={styles.sectionDescription}>                Read the docs to discover what to do next:</Text></View><LearnMoreLinks /></View></ScrollView></SafeAreaView></>  );};const styles = StyleSheet.create({  scrollView: {    backgroundColor: Colors.lighter,  },  engine: {    position: 'absolute',    right: 0,  },  body: {    backgroundColor: Colors.white,  },  sectionContainer: {    marginTop: 32,    paddingHorizontal: 24,  },  sectionTitle: {    fontSize: 24,    fontWeight: '600',    color: Colors.black,  },  sectionDescription: {    marginTop: 8,    fontSize: 18,    fontWeight: '400',    color: Colors.dark,  },  highlight: {    fontWeight: '700',  },  footer: {    color: Colors.dark,    fontSize: 12,    fontWeight: '600',    padding: 4,    paddingRight: 12,    textAlign: 'right',  },});export default App;

where I get the the following error:

Property 'HermesInternal' does not exist on type 'Global & typeof globalThis'.

as you can see here:

enter image description here

Is there any way to handle this?

Thanks!

How to give array of spans bottom border at specific index? ReactJS

$
0
0

so what this does it checks the words that are inputted by user and compares to text array, how can i give bottom Border to a span which should be inputted next?

return <span>{val}</span>

FirebaseFirestore.Timestamp vs firebase.firestore.Timestamp on React Native client and Admin Node server

$
0
0

I'm trying to solve an issue that seems like it should be an easy fix, but I can't find anything in the documentation about it, and there doesn't seem to be any questions regarding it.

I'm building an app with React Native, where we create various documents relating to the app, and send these to a Firebase function running an express server that connects to Firestore with the Admin SDK for node@10. My issue is trying to find some sensible way to represent dates without having to convert everything back and forth every time, since there are quite a few date fields in my documents/subdocuments. I initialize the react native firebase connection with import * as firebase from firebaseand firebase.initializeApp(...config) here. The Timestamp object for this library has type firebase.firestore.Timestamp. Meanwhile, on my server, I initialize with import * as admin from 'firebase-admin' and admin.initializeApp(credential, ...config). Here, the type of Timestamp is FirebaseFirestore.Timestamp, and comes from the google-api library, instead of the firestore library. When I then send an object with this type from the server to the client, or the other way around, typescript compilation fails because the two types are incompatible.

My most recent attempt at doing this was to use the Date object, but when I send this to Firestore, it automatically converts it to a FirebaseFirestore.Timestamp object, which leads me back to my original problem of not wanting to manually convert every object before I typecheck it (on each end of the REST API).

Any tips or hints on how I can fix this? I know I don't have a reproducible example here, but I don't really see the need for it, since it's more of a type issue than actual programming.

Thanks for any help!

(I also can't use @firebase/testing's initializeTestApp() because of this, because FirebaseFirestore.Firestore and firebase.firestore.Firestore are two different types, which I don't know if in the same category of error as this one.)


React-Native custom Text component with Typescript : "Type \{\} is missing..."

$
0
0

I've been trying to implement the following custom Text component in React Native.

import React from 'react';import { Text as RNText, TextStyle } from 'react-native';export interface TextProps {  children: React.ReactNode;   type?: 'title' | 'large' | 'medium' | 'small';  weight?: 'thin' | 'light' | 'regular' | 'bold';  color?: string;  style?: TextStyle;};const Text = ({  children,  type,  weight,  color,  style = {}}: TextProps) => {  const fontSize = () => {    switch (type) {      case 'title':        return 24;      case 'large':        return 28;      case 'medium':        return 18;      case 'small':        return 14;      default:        return 16;    }  };  const fontFamily = () => {    switch (weight) {      case 'thin':        return 'Lato-Thin';      case 'light':        return 'Lato-Light';      case 'regular':        return 'Lato-Regular';      case 'bold':        return 'Lato-Bold';      default:        return 'Lato-Regular';    }  };  return (<RNText       style={{        fontFamily,         fontWeight,         color: color || '#fff',         {...style}      }}>      {children}</RNText>  );};export default Text;

However, I have an error on <RNText> : "Type {} is missing the following properties from type 'Text': measure, measureInWindow, measureLayout, setNativeProps and 9 more"

If i remove the style props of the <RNText> component, I've got another error in VSCode: "Conversion of type {children: React.ReactNode} to type Text may be a mistake because neither type sufficiently overlaps with the other. If it was intentional, convert the expression to unknown first"

Seems like I would have the set the wrong type for the children props ?

Thanks in advance !

What is the proper way to make navigation.goBack action to be processed immediately?

$
0
0

Due to the nature of our app, it has some heavy data traffic over the bridge between native and javascript thread.

To decrease this communication over the bridge and moving some js implementations to the native side is another concern but for the sake of the smooth user experience, i wanted to give some priority to react-navigation events so they can be processed first just to achieve to increase its perceived performance by the user.

I mean whenever a user wants to return the previous screen and press the go-back button for this purpose, going back must be immediate despite the bridge being busy with other stuff.

Here is my simple implementation of back button and onPress event. It simply fire navigation.goBack(null) but when my app is busy with processing other things, goBack action is delayed almost 1-2 seconds. This leads a bad user experience.

  import { HeaderBackButton } from 'react-navigation-stack';  ...  const goBackAction = () => { navigation.goBack(null); };  headerOptions.headerLeft = () => <HeaderBackButton onPress={goBackAction} />;  ...

Can i give priority to react navigation.goBack action to be processed immediately?

Can I tell useMemo to skip null values in its dependency array?

$
0
0

I have a useMemo hook that wraps a component that only needs to re-render when its prop has certain shape (must not be null and must include a timestamp property).

In the below example my layout prop may have different values like null, {timestamp:1, ...}, again null...etc.

My aim is to utilize useMemo for allowing my component only re-render if layout has timestamp, otherwise it must return the memoized one.

import React, { useMemo } from "react";export default ({layout}) => {  const {timestamp} = layout || {};  return useMemo(() => <div>current state: {timestamp}</div>, [timestamp]);}

How can I initialize a class instance in a stateless function component in React?

$
0
0

Using a stateful pattern, I usually initialize a kind of helper class in my constructor and consume its methods in some component lifecycle methods like below:

class StatefulComponent extends Component {  constructor(props) {    super(props);    this.helper = new HelperClass();  }  componentDidMount() {    this.helper.doSomething();  }}

Now, I wanted to convert the same logic into a stateless function component like this:

const StatelessFunction = (props) => {   this.helper = new HelperClass();   useEffect(() => {     this.helper.doSomething();   }, []);}

But I worried when I saw that this component is being called every prop change from the beginning.And this made me think that my class instance is being created over and over. Am I wrong? Is there anything I can do for preventing re-creation of my class and use a ref instead?

I came across useRef but not sure if it fits my case.

Property 'blur' does not exist on type 'Input'

$
0
0

I am using the useRef hook to pass a ref property into my custom FieldInput component. This is then used for the validation of my form.

const fieldRef = useRef();...    const handleSubmitForm = (    values: FormValues,    helpers: FormikHelpers<FormValues>,  ) => { ....    fieldRef.current.blur();    helpers.resetForm();  };

However, I get an error on fieldRef.current that Object is possibly 'undefined'.. In order to fix that, I made these changes:

const fieldRef = useRef<Input>(null);...fieldRef.current?.blur();

However, I still get an error that Property 'blur' does not exist on type 'Input'.. Here, Input is imported from native-base. Due to this, I get type errors/warnings when I submit the form. An unhandled error was caught from submitForm()How can I get rid of these errors?

The full scenario is replicated here in a codesandbox: https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

Viewing all 6214 articles
Browse latest View live


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