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

Reference Type Within itself, TypeScript

$
0
0

I'm trying to pass types (screen param types) to a field based on the value (screenName) entered.

This is the navigation prop.

export interface IEditProfileStackNavigatorProps<RouteName extends keyof EditProfileRoutes> {  navigation: StackNavigationProp<EditProfileRoutes, RouteName>;  route: RouteProp<EditProfileRoutes, RouteName>;}

and the routes

export type EditProfileRoutes = {  Options: undefined;  Name: undefined;  Username: { token: string };  Bio: undefined;  Location: undefined;  VerifyUser: {    screenToNavigateTo: keyof Omit<EditProfileRoutes, 'VerifyUser'> | keyof ManageAccountRoutes;    params: any;  };};

I would like params to receive param types of a screen based on the screen name inserted in the navigation function.

navigation.navigate('VerifyUser', {  screenToNavigateTo: 'Username',  params: { some: 'value' } })}

so that if the screen inserted in screenToNavigateTo is username the param type will be { token: string } and for the rest it will be undefined.

My approach was doing something like

export type EditProfileRoutes = {  Options: undefined;  Name: undefined;  Username: { token: string };  Bio: undefined;  Location: undefined;  VerifyUser: {    screenToNavigateTo: keyof Omit<EditProfileRoutes, 'VerifyUser'> | keyof ManageAccountRoutes;    params?:EditProfileRoutes['VerifyUser']['screenToNavigateTo'];  };};

but this seems not to work


How to debug React Native project created with Expo using TypeScript

$
0
0

I created an Expo boilerplate project that is using TypeScript.

When I run the app with expo start, the Chrome debugger opens up at http://localhost:19001/debugger-ui/, but in the devtools I can only see .js files:

enter image description here

How can I get my .tsx sourcefiles to show up?

I have "sourceMap": true, in .tsconfig.json and the .map files are generated along the .js files. Any more configuration I am missing here?

Displaying two Array items in Picker View

$
0
0

I am new to react and i want display array item into pickerview for selection

NOTE : Consider i can not modify structure of both the API_URL and env const

only way i can access the value is API_URL[env.url1]

My entire code is as below :

import React, { Component } from 'react';import { Picker, SafeAreaView, Text } from 'react-native';export default class App extends Component {  state = {    hand: 'right',   }  render() { const API_URL: any = {    url1: 'http://xyz',    url2: 'http://abc',    url3: 'http://pqr',    };    const env: any = {    url1: 'url1',    url2: 'url2',    url3: 'url3'};    return (<SafeAreaView style={{flex:1}}><Text style={{ color:'black', fontWeight:'900', fontSize: 18, padding:30}}> Scegli tipo </Text><Text style={{ color:'black', fontWeight:'900', fontSize: 18, padding:30}}> {API_URL[env.url1]} </Text><Picker          selectedValue={this.state.hand}          onValueChange={hand => this.setState({ hand })}          style={{ width: 160, postion: 'absolute',fontSize:10 }}          mode="dropdown"          itemStyle={{ color:'red', fontWeight:'900', fontSize: 18, padding:30}}><Picker.Item label="Right Hand" value="right" /><Picker.Item label="Left Hand" value="left" />// i want show that array  here like.    <Picker.Item label="url1" value="http://xyz" /> </Picker></SafeAreaView>    );  }}

Why my export function call every time on change TextInput

$
0
0

HI there here is my code in react and type script Why this console.log , calls every time that my text filed change trigger ..

export default function TabOneScreen({  navigation,}) {  const [out_1, set_out1] = useState('');  const [out_2, set_out2] = useState('');  const [main_device, setMain_dev] = useState('');  console.log("run every time .. on text changed .."); // on change  text run every time .. // here I had some function for init textInput value and don't want to run every time ..  return (<View style={styles.container}><View style={{      }}><TextInput          value={out_1}          onChangeText={(username) => set_out1(username)}.         />

The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement

$
0
0

I am trying to customize my imports using babel. I am following this link:

https://medium.com/@leonardobrunolima/react-tips-working-with-relative-path-using-create-react-app-fe55c5f97a21

This is my config-overrides.js

const { injectBabelPlugin } = require('react-app-rewired');const rootImportConfig = ["root-import",    {        rootPathPrefix: "~",        rootPathSuffix: "src"    }];module.exports = config => injectBabelPlugin(rootImportConfig, config);

Package.json:

"scripts": {"start": "react-app-rewired start","build": "react-app-rewired build",

Currently, this gives me an error that:The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement

Hence, I installed

nom install customize-cra react-app-rewired --dev

and changed 'react-app-rewired' to 'customize-cra' in my js file as suggested here:https://github.com/arackaf/customize-cra#available-plugins

However, that still doesn't work since the injectBabelPlugin is also depreciated. What the function should I use here then? I tried the config files from here but it doesn't work from me either. It's src-functionality is also different.

https://github.com/timarney/react-app-rewired/issues/348

How can I fix my config file and imports? Instead of

import { ResultAlert } from '../../components/alerts/ResultAlert';

I want to do something like this:

import {ResultAlert} from '~/components';

How to use react-native-testing-library getByRole

$
0
0

I'm trying to use getByRole in react native testing library but can't for the life of me figure out the syntax

Component in question-

<Text   accessibilityRole={'button'}  accessibilityLabel={'upvote count'}  style={[styles.upvoteText, styles.upvoteCount]}>  {upvoteCount}</Text>

and my code

expect(getByRole('button', {name: 'upvote count'} as MatcherOptions)).toBe(2)

VSCode react native no import errors detected in code

$
0
0

I have been using vscode for couple of years but recently with version 1.45 i don't see any errors detected while i code . For example , it does not validate whether the import statement is valid nor the modules inside is valid or not . Earlier it used to clearly mark it in red if a module is not found in the import statement but still declared .

Vscode treats unknown variables as "any" and does not show any error unless i run it in the simulator.

Secondly, whenever i type an object if an import statement is found i used to see the option highlighted and now i don't see that either.

Any clue on why this behavior in vscode?.

Change image url using ternary operator when a condition is met

$
0
0

When the user shakes the phone I want to change an image, and let it stay rendered that way. With this I can change the image but it goes back once the condition is not fulfiled:

function Shaker(){useEffect(() => {        const subscription = accelerometer.subscribe(({ x, y, z }) =>            setSensorData({ x, y, z })            );  }, []);const acceleration = Math.sqrt(sensorData.x * sensorData.x + sensorData.y * sensorData.y + sensorData.z * sensorData.z);const imgchange = acceleration > 12 ? imgThatIwantToRenderAfterConditionAndStay.png : 'DefaultImg.png' ;return (<View><Image style={{ width: 100, height: 100 }} source={{ uri: imgchange }} /></View>}

When I created a boolean and passed it instead of acceleration > 12 i got read only error:

const accelerationobtained = false;if (acceleration > 12) { accelerationobtained = true; }const ifimg = accelerationobtained ? imguri : 'https://www.nicepng.com/png/full/416-4167329_shot-glass.png' ;

I think my solution is dumb and I didnt expect it to work so I want to get educated on how should I handle such case.


How can I add a testId attribute to a React Native component for Testing Library when TypeScript prevents me?

$
0
0

I'm writing a React Native components using TypeScript and testing them with React Native Testing Library.

I want to put a testId attribute on a React Native component like so:

<TextInput testId="foo" />

And then refer to it in a test like so:

it('receives a search string', () => {  const { getByTestId } = render(<FooComponent />);;  const textBox = getByTestId("foo");  fireEvent.changeText(textBox,"some fake text");  expect(textBox.value).toEqual("some fake text");});

But TypeScript won't allow me to put a testId attribute on a component.

How do I get TypeScript to recognize the added attributes like testId from @testing-library/react-native.

Type issue in Typescript React-native styled-component

$
0
0

I am trying to create a TouchableOpacity using styled-component in react-native and was working successfully but since i am using typescript its showing some error when using style flowDirection: 'row'

here is my code

interface IDefaultStyle {  style?: object}const RootContainer = styled.TouchableOpacity((props: IDefaultStyle) => ({  flexDirection: 'row',  ...props.style}))

And the type error is

Argument of type '(props: IDefaultStyle) => { flexDirection: string; } | { flexDirection: string; }' is not assignable to parameter of type 'TemplateStringsArray'.

Type Error

And when i remove flexDirection and add any other style type. the error is gone.

The same issue is seen in styled-components Text when fontWeight: 'bold' is given

My package.json

{"name": "@appmaker/ui","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint ."  },"peerDependencies": {"react": "16.9.0","react-native": "0.61.2"  },"devDependencies": {"@babel/core": "7.6.4","@babel/preset-typescript": "^7.7.2","@babel/runtime": "7.6.3","@react-native-community/eslint-config": "0.0.3","@types/jest": "^24.0.20","@types/react": "^16.9.11","@types/react-native": "^0.60.22","@types/react-test-renderer": "^16.9.1","@types/styled-components": "^4.1.20","@typescript-eslint/eslint-plugin": "^2.5.0","@typescript-eslint/parser": "^2.5.0","babel-jest": "24.9.0","babel-plugin-styled-components": "^1.10.6","jest": "24.9.0","metro-react-native-babel-preset": "0.51.1","prettier": "^1.18.2","react-test-renderer": "16.9.0","tslint": "^5.20.0","tslint-config-prettier": "^1.18.0","tslint-config-standard": "^8.0.1","tslint-eslint-rules": "^5.4.0","tslint-react": "^4.1.0","typescript": "^3.6.3","typescript-plugin-styled-components": "^1.4.3"  },"jest": {"preset": "react-native","moduleFileExtensions": ["ts","tsx","js","jsx","json","node"    ]  },"bit": {"env": {"compiler": "bit.envs/compilers/react-typescript@3.0.27"    },"componentsDefaultDirectory": "components/{name}","packageManager": "npm"  },"dependencies": {"i": "^0.3.6","npm": "^6.12.0","prop-types": "^15.7.2","react-native-image-slider": "^2.0.3","react-native-image-slider-box": "^1.0.5","react-native-snap-carousel": "^3.8.3","styled-components": "^4.4.0"  }}

it will be greatly appreciated if someone could help me with this

Editcomponent usage

/** * ## AuthorView  | SellerView * Component to show Author info * @param props */const AuthorView = (props: IProps) => {  const { name, style, imageUrl, rating, subtext, onPress } = props  // if imageUrl is not provided use default star icon  const imageSource = imageUrl ? { uri: imageUrl } : require('../../icons/star-grey.png')  return(<RootContainer onPress={onPress} style={style}><ImageViewContainer><ImageView              defaultImage={imageUrl ? false : true}              source={ imageSource }            /></ImageViewContainer><RightContainer><Name>{name}</Name><View style={{ flexDirection: 'row' }}>            {rating && <RatingView style={{ marginRight: 3 }} rating={rating} />}<SubText>{subtext}</SubText></View></RightContainer></RootContainer>  )}export default AuthorView

Changing interface depending on string input

$
0
0

I saw something cool within the React Navigation type.d.ts file and wondered how I could recreate some of the functionality.

It's this line I'm trying to understand

export declare type StackNavigationProp<ParamList extends ParamListBase, RouteName extends keyof ParamList = string> = NavigationProp<ParamList, RouteName, StackNavigationState<ParamList>, StackNavigationOptions, StackNavigationEventMap> & StackActionHelpers<ParamList>;

It seems that the StackNavigationProp can be a unique prop depending on the string that it's given for example 'Welcome'.

type RootStackParamList = {  Welcome: undefined;  SignUp: undefined;  Forgot: undefined;};interface RootScreenProps {  navigation:StackNavigationProp<RootStackParamList, 'Welcome'>}

Is there anyone out there who understands this better and could write up a simple example?

Proper Typescript type for a reused screen in react-navigation v5

$
0
0

For most of the cases, I follow a simple pattern to type any screen under react-navigation v5:

// Params definitiontype RouteParamsList = {    Screen1: {        paramA: number    }    Screen2: undefined}// Screen1type Props = StackScreenProps<RouteParamsList, 'Screen1'>export const Screen1: React.FC<Props> = ...

That works perfectly.

I can't figure out the proper types for a case when I'd want to reuse the Screen1 for different navigators though:

// Params definitiontype RouteParamsListShop = {    Screen1: {        paramA: number    }    Screen2: undefined    Screen3: undefined}type RouteParamsListFeatures = {    Screen1: {        paramA: number    }    Screen4: undefined}// Screen1type Props = StackScreenProps<RouteParamsListShop, 'Screen1'> | StackScreenProps<RouteParamsListFeatures, 'Screen1'> // Tried thisexport const Screen1: React.FC<Props> = ...

As I commented, I tried to have a union type covering both cases. It allows to get the parameters from the route properly, but navigate method breaks:

This expression is not callable. Each member of the union type '/* Route info here */' has signatures, but none of those signatures are compatible with each other.ts(2349)

Is there a way to properly type it, or I rather have to change the structure of my navigation to make the screen only part of one route? (alternatively, create 2 wrappers for different navigation).

Typescript React | Adding 'as const' on variable has different behavior in playground and IDEs (VSCode, WebStorm)

$
0
0

I know I've added react-native even though this is really just a reactjs question.

The code

const ScreenStates = {  DEFAULT: 0,  ERROR: -1,  SUCCESS: 1,} as const;type State = {  currentState: typeof ScreenStates[keyof typeof ScreenStates];};type Props = undefined;class TestComponent extends React.Component<Props, State> {  state = {    currentState: ScreenStates.DEFAULT,  };  randomFunc = () => {    switch (this.state.currentState) {      case ScreenStates.SUCCESS: {        break;      }      default:        break;    }  };  render() {    return null;  }}

The Issue

In VSCode or WebStorm, it will say that Type '1' is not comparable to type '0'.ts(2678) but the error goes away if I remove the as const from ScreenStates variable.

On the TS Playground or CodePen it doesn't show it as a problem.

enter image description here

What I've tried so far

  1. Changing the number types to strings (0 becomes '0', error becomes '-1', success becomes '1')
    • Doesn't work
  2. Removing 'as const', breaks because any number can then be considered as okay
  3. Re-typing state variable with State type works correctly (with as const), but I shouldn't need to because I already added the component?

Edit 3:

  1. At first I thought it's because I'm redeclaring it in the class that's why I need to retype it again as State, but if I redeclare it with an empty object it tells me that a certain property is missing; which means that it knows that the redeclared state is actually of State and yet it thinks that currentState can only have one value? What am I missing?enter image description here

Relevant packages in package.json

"@babel/preset-typescript": "^7.12.7","@typescript-eslint/eslint-plugin": "^4.8.2","@typescript-eslint/parser": "^4.8.2","typescript": "^4.1.2"

How to rewrite this function to a interface?

$
0
0

My goal is to write everything in interface, TypeScript. It's for React Native.

This is the function I am unable to put into an interface. The current solution is to put it outside the interface but the import would be ugly e.g import AudioRecorderModule, { addAudioRecorderEventListener } from '...'

export const addAudioRecorderEventListener = (  listener: (data: number[]) => void,) => eventEmitter.addListener('read', listener);

AudioRecorder.module.ts

import {NativeEventEmitter, NativeModules} from 'react-native';import AudioRecorderInterface from './AudioRecorder.d';const {AudioRecorderModule} = NativeModules;const eventEmitter = new NativeEventEmitter(AudioRecorderModule);export const addAudioRecorderEventListener = (  listener: (data: number[]) => void,) => eventEmitter.addListener('read', listener);export default AudioRecorderModule as AudioRecorderInterface;

AudioRecorder.d.ts

export default interface AudioRecorderInterface {  startAudioRecordingAsync(): Promise<null>;  stopAudioRecordingAsync(): Promise<null>;}

TypeError: null is not an object (evaluating '_reactNativeWifiReborn.default.connectToProtectedSSID') when using wifi -reborn library

$
0
0

I am trying to get wifiname by using react-native-wifi-reborn library but when i try to implement methods which are mention in github page of this library but its getting error.can any one tell me how to use this library by example.


Typescript picks wrong interface for type checking for React Native component state

$
0
0

Some of my classed do not pass type checking by ESLint with Typescript because of this error:

  Object literal may only specify known properties, and 'selectedIndex' does not exist in type '{ zoomLevel: number; markerPointId: number; isLocationEnabled: boolean; markerIdFromProps: number; userPosition: { latitude: number; angle: number; longitude: number; }; mapRotate: boolean; darkMode: boolean; selectedRock: { ...; }; isModalVisible: boolean; isRockModalVisible: boolean; points: any[]; }'.

Example of this code:

export interface MyProps extends ViewProps {  ...  initialPage: number;  ref?: React.Ref<MyComponent>;}interface MyState {  selectedIndex: number;}export default class MyComponent extends React.Component<  MyProps,  MyState> {  constructor(props: MyProps) {    super(props);    const {initialPage} = props;    this.state = {      selectedIndex: initialPage    };  }...}

Error is on init state and in using state.

React native with typescript - how to use the useRoute from @react-navigation/native with typescript

$
0
0

I'm trying to get my incident object from route.params but I don't know how to do it to make typescript recognize this prop.

Here is the function that navigate to my Detail page passing incident to params:

const navigateToDetail = (incident: IncidentProps): void => {    navigation.navigate('Detail', { incident });  };

And Here is part of Detail page code where I try to get this object from route.params:

type IncidentRouteParams = {  incident: IncidentProps;}const Detail: React.FC = () => {  const navigation = useNavigation();  const route = useRoute();  const incident = route.params.incident;

I think I need to pass this IncidentRouteParams type somehow to const route = useRoute()

Thanks in advance.

Here is the image with the error:

EDIT:

I did like this, and it worked, but I don't know if it is the right way:

  const route = useRoute<RouteProp<Record<string, IncidentRouteParams>, string>>();  const incident = route.params.incident;

Return json object from resolved promise and assign it after it is loaded

$
0
0

I have a method in a class which returns JSON object and then outside the class in a function I create an instance of this class, call one of the methods and expect to read returned JSON values. But what happens is that the variable assigned to the method is called at the very start before method even collects the data resulting in undefined. I tried short circuit (&&) which worked for me before, but not this time. I also tried using hooks instead of let and returning that, which ultimately worked for me but for some reason, it was looping as if I put it in while(1). All the methods were taken from an SQLite tutorial and modified.

function Screen() {    const a = new App();    let prodReturned = null;    prodReturned = a.getProducts();    return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>text: {prodReturned && JSON.stringify(prodReturned)}</Text></View>    );}export default class App extends Component {getProducts() {        let products=[];        this.listProduct().then((data) => {            products = data;            console.log(typeof(data),data,'this returns object type and correct json form')            return products;        }).catch((err) => {            console.log(err);           })}listProduct() {        return new Promise((resolve) => {            const favdrinks = [];            this.initDB().then((db) => {                db.transaction((tx) => {                    tx.executeSql('SELECT p.favorites FROM drinks p', []).then(([tx, results]) => {                        console.log("Query completed");                        var len = results.rows.length;                        for (let i = 0; i < len; i++) {                            let row = results.rows.item(i);                            console.log(`Drinks favorited: ${row.favorites}`)                            const { favorites } = row;                            favdrinks.push({                                favorites                            });                        }                        console.log(favdrinks);                        resolve(favdrinks);                    });                }).then((result) => {                    this.closeDatabase(db);                }).catch((err) => {                    console.log(err);                });            }).catch((err) => {                console.log(err);            });        });}}

How do I make sure to call the method and assign the return value to a variable once it is prepared to do so?

React Native SectionList: What are the correct TypeScript types

$
0
0

I'm building a React Native app using TypeScript. I'm trying to use a SectionList. I followed the docs, and here is my code:

  renderSectionHeader = ({ section: { title } }: { section: { title: string } }) => (<ListItem title={title} />  );  render() {    const { sections } = this.props;    return (<SafeAreaView style={styles.container}><SectionList          keyExtractor={this.keyExtractor}          sections={[            {title: 'Title1', data: ['item1', 'item2']},            {title: 'Title2', data: ['item3', 'item4']},            {title: 'Title3', data: ['item5', 'item6']},          ]}          renderItem={this.renderItem}          renderSectionHeader={this.renderSectionHeader}        /></SafeAreaView>    );  }

But the line renderSectionHeader={this.renderSectionHeader} throws the following TSLint Error:

[ts]Type '({ section: { title } }: { section: { title: string; }; }) => Element' is not assignable to type '(info: { section: SectionListData<any>; }) => ReactElement<any> | null'.  Types of parameters '__0' and 'info' are incompatible.    Type '{ section: SectionListData<any>; }' is not assignable to type '{ section: { title: string; }; }'.      Types of property 'section' are incompatible.        Type 'SectionListData<any>' is not assignable to type '{ title: string; }'.          Property 'title' is missing in type 'SectionListData<any>'. [2322]

Are the types of SectionList broken? Or is the example wrong? Or am I doing something wrong?

Module not found. Can't resolve 'assets/styles/constants'

$
0
0

I've wanted to add Expo in my React Native project to start it in web browser. After doing that, I try to import file 'assets/styles/constants.ts'. This is my tsconfig.json:

tsconfig.json

This is constants.ts:

constants.ts

And here I try to import this file:

DropdownAlertCustom.tsx

After that, I get this error:

error message

What am I doing wrong? And how I can fix it?

Viewing all 6213 articles
Browse latest View live


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