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

React-Localization setLanguage() does not update the page

$
0
0

What am I trying to achieve

Currently, I am trying to implement localization within our current React-Native project.

To do this, I choose the following package: React-Localization

Our project makes usage of React-Native in combination with TypeScript.

What is the problem

I have written a function to set the language from "en" to "nl".

Then I have two pages:

  • Home (contains the function to change the language & has a Text element)
  • Settings (has a Text element)

Only the text on the Home page gets updated. The text element on the Settings page is not getting translated. Also my header and bottom navigation are not translated.

What code am I using

To switch the language

    switchLanguage() {
        if (translationStrings.getLanguage().toLowerCase() == 'nl') {
            translationStrings.setLanguage('en');
        } else {
            translationStrings.setLanguage('nl');
        }
        this.setState({});
    }

Translations

export const translationStrings = new LocalizedStrings({
    en: {
        tempTest: "English test one",
        tempTest2: "English test two"
    },
    nl: {
        tempTest: "Dutch test een",
        tempTest2: "Dutch test twee"
    }
});

Examples of the elements that I am trying to translate.

// This is on the home page so it works.
                <Text>
                    {translationStrings.tempTest}
                </Text>

// This is on the settings page and it does not work.
                <Text>
                    {translationStrings.tempTest2}
                </Text>

Also, the header and bottom navigation is not updating/getting translated.

Could someone give me some insight into what I am exactly doing wrong?

It feels like I should give the application a sign that everything has been translated and that it should reload or something.


How to crash a React Native app that is Jenkins checked by type script to not have bad code?

$
0
0

My Jenkins server will audit code like due to Typescript checking.

let x = []
x()

I want to simulate a real crash, not their test crash.

Switching from Angular to React [closed]

$
0
0

I have a background in Angular + Typescript/ .NET-Core Web developement. Is it difficult to shift gears into developing React Native App (mobile)? Do I have the advantage going into this considering my past exp with Angular? I heard they are very different.

React-Native header is not getting translated

$
0
0

So I managed to get translation working pretty good in my TypeScript React-Native application. Everything is getting translated (every page and the bottom navigation), except for the header titles.

The code that I am using to achieve this goal looks like below:

const NewsPageStack = createStackNavigator({
    News: {
        screen: News,
        navigationOptions: ({navigation, navigationOptions}) => ({
            title: translationStrings.news.toUpperCase(),
            headerTintColor: COLORS.primaryLightBlue,
            headerTitleStyle: Styles.headerTitleStyle,
        }),
    }
});

The translations are done with react-localization. I am pretty sure that it has something to do with the StackNavigator, but I have no clue how to solve this.

Create and publish a reusable React Native UI component library

$
0
0

I'm trying to create a component library (similar like Kitten UI, Ant design RN and etc) for React Native and I'm wondering if there is any simple example repo or boilerplate (with Typescript) for that? Not including/bridging any native modules but just React Native UI components.

Add strong typing for react navigation props

$
0
0

I'm using typescript in my react-native project(expo).

The project uses react-navigation, so on my screens I can set navigationOptions and I have access to the prop navigation.

Now I'm trying to strongly type these so I get hints for what properties are available to set.

interface NavStateParams {
    someValue: string
}

interface Props extends NavigationScreenProps<NavStateParams> {
   color: string
}

class Screen extends React.Component<Props, any> {
    // This works fine
    static navigationOptions: NavigationStackScreenOptions = {
        title: 'ScreenTitle'
    }
    // Does not work
    static navigationOptions: NavigationStackScreenOptions = ({navigation, screenProps }) => ({
        title: navigation.state.params.someValue
    })
}

What would be the best way to handle react-navigation as props for components.

React Typescript Error using static object

$
0
0

I am building a react native app and am using react-native-reanimated and react-navigation-animated-switch to try and create an animation when changing screens. I am also using typescript. Just following react-navigation's guide I can't figure out why there example doesn't work for me. https://reactnavigation.org/docs/en/animated-switch-navigator.html

import createAnimatedSwitchNavigator from 'react-navigation-animated-switch';
import { Transition } from 'react-native-reanimated';

const MySwitch = createAnimatedSwitchNavigator(
 {
Home: HomeScreen,
Other: OtherScreen,
},
{
transition: (
  <Transition.Together>
    <Transition.Out
      type="slide-bottom"
      durationMs={400}
      interpolation="easeIn"
    />
    <Transition.In type="fade" durationMs={500} />
  </Transition.Together>
),

} );

All the code that uses Transition I get a typescript error that Transition refers only to a type. Transition has a static objects Together, In etc but it is not found. Also it the package does have ts.d file.

Thanks

throw error failed on promisse typescript

$
0
0

Im trying to create a netInfo checker on my API service. This is my job to connect with an endpoint, and i need to create a netInfo check service to handle connection errors :

loginExists(username)
      .then((status: string) => {
        setLoading(false);
        if (status == '200' || status) {
          const checkSAPData = checkUserSAPMock(username);
          if (checkSAPData) {
            navigation.navigate('LoginPassword', { document: username, sapData: checkSAPData });
          } else {
            navigation.navigate('LoginPassword', { document: username });
          }
        }
      })
      .catch(error => {
        console.log('myerror: ' + JSON.stringify(error));
        setLoading(false);
        const checkSAPData = checkUserSAPMock(username);

        if (checkSAPData) {
          if (checkSAPData.Motorista.item.Autorizacao === "S")
            navigation.navigate('SignUp', { data: checkSAPData });
          else
            navigation.navigate('LoginPassword', { document: username, sapData: checkSAPData });
        } else
          navigation.navigate('SignUp', { isNewUser: true, document: cpf });
      }); 

Here I go to API service to perform:

export function loginExists(username: string) {
  const headers = new Headers({
    'Content-Type': 'application/json',
  });

  // TODO: REMOVE
  // debug
  // if (username === '00000000000') {
  // return API.get(`motoristas/cpf/09503054990/existe`);
  // }
  return API.get(`motoristas/cpf/${username}/existe`);
}

My netInfo checker, where i throw the error:

get(endpoint: string, headersProp?: Headers | string[][] | Record<string, string>): Promise<any> {

    return ConnectionChecker.getConnection().then(state => {

      let headers = {
      };

      if (headersProp) {
        headers = { ...headers, ...headersProp };
      }

      if (state.isConnected) {
        return fetch(`${this.url}/${endpoint}`, {
          method: 'GET',
          headers
        });
      } else {

        //Criar arquivo de constantes com erros da aplicacao/genericos.
        const errorData = {
          type: 'connection',
          title: 'title',
          message: 'message'
        };

        throw new Error(JSON.stringify(errorData));
      }


    }).then(this._handleError)
      .then(this._handleContentType)
      .catch(this._handleErrorCatch);
  }

And finally my handleErrorCatch:

_handleErrorCatch: async (error: any) => {
    console.log('entrei aqui 1: ' + error);
    throw new Error(error);
  }

The problem is: my error object is not correct. console.log() gives me this message:

myerror: {"line":185244,"column":30,"sourceURL":"http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false"}

But this is my throw error:

{"type":"connection","title":"title","message":"message"}

anyone can helps me? Thanks guys!!! o/


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?

How to extend React Component prop typing without changing all usages of React.Component

$
0
0

I want to make testID a prop available for all React.Component instances for native testing. Currently, I am adding it to prop type of all the components that are using it. Is there any way where, for example I can define react/index.d.ts and override the Component prop type to include {testID?: string}?

EDIT:

// types/react/index.d.ts

import 'react'
import { Attributes, ClassAttributes } from 'react'

declare namespace react {
  interface IntrinsicAttributes extends Attributes {
    testID?: string
  }
  interface IntrinsicClassAttributes<T> extends ClassAttributes<T> {
    testID?: string
  }
}

I tried the above override, but it's not working, but if I copy the whole react typing file in and then make above changes, it works fine. So I just need proper overriding technique. Can someone please help me in that?

react-native-paper code completion for jetBrains ide

$
0
0

Intellij uses @types/* libraries for for helping with react code completion. react-native-paper doesn't have this kind of seperate library.As its author claims it does ship with types inside it:

https://github.com/callstack/react-native-paper/issues/1492

Well I couldn't get it working how much I tried so I asked it here as the author suggested.What I tried:

  1. Added 'allowJS' : true to your jsconfig.json or tsconfig.json file since there was no file like that I created it myself(https://www.jetbrains.com/help/idea/typescript-support.html)
  2. The next thing going to Setting->Language And FrameWorks->Javascript->Libraries->Add... click the above plus button attach files and added the directory of the library.

So How do you guys got it working?Please let us know.Thank you so much.

Mutually exclusive attributes using Flow

$
0
0

I'm building a UI component in the company I work for. It's in React Native and it uses Flow to typecheck. Thing is I want the components to have certain variants but they force me to have nothing but booleans for components attributes. And I'd like the components to disallow the use of more than one variant.

Let's say my component <Button> has two variants: primary and secondary. If I could use an attribute variant it would be easier because I would be able to use variant='primary'. But I can't do that. It has to be primary=true but I have to make it exclusive: if I have primary:true you shouldn't be allowed to use secondary:true in the same component.

I'been checking the docs but I couldn't find a way. And it makes sense, why would you have one? Just stop using boolean's for everything, right?

Question is: Is there a way?

How to deal with SQLite migrations in React-Native using TypeORM?

$
0
0

I am writing a React-Native app which heavily relies on local storage, and have chosen TypeORMto handle this.

I am now entering a phase where my project is live, and I want to add new functionalities that require an adjustment to my datamodel. To start, I have used the react-native-example project. I have built my datamodel on this and would now like to implement a migration into it.

There seems to be no definitive manual/guide on how to perform migrations on React-Native. Since I don't have access to the databases of my users, I can't run the migrations manually. So far, I found out that there is a 'migrationsRun' option in the connection settings which can be set to true, forcing migrations to be executed at every launch of the app, if needed.

Question then is: How should the actual migrations be created, what should they look like (plain sql queries?), and where should I put them?

Any guidance on migrations in a react-native app would be very helpful.

Are you able to programmatically generate screens inside React Navigation Tab Navigator

$
0
0

Using React-Navigation, I am trying to generate an unknown number of tabs based off of the values that I've drawn from an array, and pass the data from that array value into the screen. For example, if I have 2 accounts, I would expect 2 tabs with screens for each one, but if I have 5 accounts, there are 5 tabs, with their own screens that are generated programatically from the values that are sent across from the database.

What I have so far, and what I am trying to do is:

interface Account {
  accountNumber: string;
  balance: number;
}

const accounts: Account[] = [
  { accountNumber: '1', balance: 10 },
  { accountNumber: '2', balance: 15 },
  { accountNumber: '3', balance: 20 }
];


class AccountScreen extends React.Component<Account>{
  constructor(props: Account) {
    super(props)
  }

  render() {
    return (
      <View>
        <Text>This is an Account</Text>
        <Text>Account Number: {this.props.accountNumber}</Text>
        <Text>Balance: £{(this.props.balance/100).toFixed(2)}</Text>
      </View>
    );
  }
};

const accountScreens = {};

accounts.forEach(account => accountScreens[account.accountNumber] = { screen: AccountScreen, props: account }); 
// SOMETHING LIKE THIS

export default AccountNavigator = createMaterialTopTabNavigator(accountScreens);

The screens render with the correct tabs, but the values within each account are not passed down through props. I know that you can't pass pass props directly into the Navigator, but I cannot figure out how that data could be accessed by the component.

Am I building this fundamentally wrong, or is there just some syntactic thing that I'm missing?

Thanks for your help!

Why is this React method not working as expected?

$
0
0

I have some code that is meant to eliminate placeholders onFocus and return them onBlur, it seems to work properly for the login text input, but not for the password one. Do you mind having a look at the code?

This is the method in question:

togglePlaceholder = (nodeType:string,localStateValue:string) => {
    switch (eval(`this.state.${localStateValue}`)) {
        case nodeType:
            return this.setState({[localStateValue]:null});
        case null:
            return this.setState({[localStateValue]:nodeType});
    }
}

I'm using eval here because I'm planning to reuse this function across multiple components to toggle their local state.

These are the components:

<TextInput style={styles.logInFormInput}
    placeholder={this.state.logInPlaceholder}
    onFocus={()=>this.togglePlaceholder('login','logInPlaceholder')}
    onBlur={()=>this.togglePlaceholder('login','logInPlaceholder')}
></TextInput>

<TextInput style={styles.logInFormInput}
    secureTextEntry={true}
    placeholder={this.state.passwordPlaceholder}
    onFocus={()=>this.togglePlaceholder('password','passwordPlaceholder')}
    onBlur={()=>this.togglePlaceholder('password','passwordPlaceholder')}
></TextInput>

Seems to be working properly for login, but not password.


TS2740 Type is missing the following properties from ReadOnly error in React Native with TypeScript app

$
0
0

Since StatelessComponent is deprecated, I am trying to turn all the components into classes.

I have an interface, for example:

interface MyInterface{
    prop1: number;
    prop2: boolean;
}

And I use it in the class:

class MyComponent extends React.Component<MyInterface> {
   ...
   public render(){...}
}

And when I try to use MyComponent like this:

<MyComponent 
    prop1={3}
    prop2={false}
/>

I get this error:

TS2740: Type {prop1: 3, prop2: false} is missing the following properties from type ReadOnly: render, context, setState, forceUpdate, and 3 more.

Is there any workaround to this?

Can not import TypeScript components with Babel custom aliases

$
0
0

I am using babel-plugin-module-resolver to import project files easily with using custom aliases. Everything seems fine on the TypeScript side. Below is the tsconfig.json:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext",
    "module": "commonjs",
    "lib": ["es6"],
    "allowJs": true,
    "jsx": "react-native",
    "noEmit": true,
    "isolatedModules": true,

    /* Strict Type-Checking Options */
    "strict": true,
    "noImplicitAny": false,

    /* Module Resolution Options */
    "moduleResolution": "node",
    "baseUrl": ".",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,

    /* Experimental Options */
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules", "babel.config.js", "metro.config.js", "jest.config.js"
  ]
}

I have a components folder in the root folder of the project and inside the folder I have 2 files.

index.tsx:

export {default as TestComponent } from './Test';

Test.tsx:

import React from 'react';
import {View, Text} from 'react-native';

export default () => {
  return (
    <View>
      <Text>Hello world</Text>
    </View>
  );
};

I am simply re-exporting the Test component from inside Test.tsx and using it in App.tsx like below:

import React from 'react';
import {StyleSheet} from 'react-native';

import {TestComponent} from 'components';

const App = () => {
  return <>
    <TestComponent />
  </>;
};

const styles = StyleSheet.create({});

export default App;

I get no warnings and no errors from the TypeScript compiler but when I run the app, I get:

Error: Unable to resolve module 'components' from 'App.tsx': components could not be found in the project.

So it seems something with the babel configuration which is like this:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./'],
        extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
        alias: {
          "components": "./components"
        },
      },
    ],
  ],
};

The funny thing is, if I import the Test component from /components/Test, skipping the re-exporting inside the index.tsx everything works like a charm:

import React from 'react';
import {StyleSheet} from 'react-native';

import TestComponent from 'components/Test';

const App = () => {
  return <>
    <TestComponent />
  </>;
};

const styles = StyleSheet.create({});

export default App;

So I really can't find out what's wrong here. Any ideas?

I am using React Native 0.61.3 and all the packages are at their latest versions.

EDIT: Also I just found out that babel.config.js is really ignored. Created an invalid configuration and it continued to work.

Typescript optional chaining error: Expression expected.ts(1109)

$
0
0

I am trying to do optional chaining in Typescript + React Native.

Let's say I have the following interfaces:

interface Bar {
  y: number
}

interface Foo {
  x?: Bar
}

and I try to run the following:

 const test: Foo = {x: {y: 3}};
 console.log(test.x?.y);

VSCode will show an error under the ?. saying the following: Expression expected.ts(1109)

Do you have any idea why this is happening or how should I fix it? Thanks.

All React Native Firebase modules must be of the same version - can't use Auth

$
0
0

I installed RNF from starter kit provided by Invertase. I am using RNF app, database, analytics, auth. Everything worked fine until I needed the auth module. It throws an error on app startup (on Android, haven't tried iOS):

    ...\node_modules\react-native\Libraries\Core\ExceptionsManager.js:86 
You've attempted to require '@react-native-firebase/auth' version '6.0.3', however, 
the '@react-native-firebase/app' module is of a different version (6.0.0).

    All React Native Firebase modules must be of the same version. 
Please ensure they match up in your package.json file and re-run yarn/npm install.

But I checked in package.json of all the modules are of version 6.0.3, and my package.json also looks good:

{
  "name": "meditationapp",
  "version": "6.0.3",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "run:android": "react-native run-android",
    "run:ios": "react-native run-ios --simulator=\"iPhone 11 Pro Max\"",
    "build:apk": "cd android && ./gradlew assembleRelease",
    "test": "jest",
    "prepare": "patch-package",
    "storybook": "start-storybook -p 7007"
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.6.2",
    "@react-native-community/netinfo": "^4.4.0",
    "@react-native-firebase/analytics": "6.0.3",
    "@react-native-firebase/app": "6.0.3",
    "@react-native-firebase/auth": "6.0.3",
    "@react-native-firebase/database": "6.0.3",
    "@typescript-eslint/eslint-plugin": "^2.3.3",
    "@typescript-eslint/parser": "^2.3.3",
    ...

Import in App.tsx:

import firebase from '@react-native-firebase/app'
import database from '@react-native-firebase/database'
import analytics from '@react-native-firebase/analytics'
import auth from '@react-native-firebase/auth'

Things I've tried:

  1. Delete node_modules and run npm install
  2. Installed v6.0.0 instead of 6.0.3
  3. Deleted android/app/build

Can't think of anything else to try, but the error does not go away. It's working fine with analytics and database, only auth is an issue.

Wrong import error with TS/JS mixing and visual studio code

$
0
0

I'm working on a react native app with both JS and TS. When I have different configurations according to the OS, I'm creating two files.

One for iOS, one for Android.

enter image description here

It works pretty well and handle things exactly the way I want, but on visual studio code when I import something from the 'firebase' file, from a typescript file I get this error

enter image description here

If I switch the .ts file in question to a .js the errors doesn't appear so it must come from the typescript configuration on Visual Studio, but don't find where..

Edit: I precise that on the compilation part, it works without error. My app is running well, it's just a visual studio code wrong error.

Anyone has got a similar problem?

Thank you

Viewing all 6207 articles
Browse latest View live