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

React Native calling actions in wrong order

$
0
0

I'm building a login form for my react native app. So there is a username field, a password field and a login button.

I have a formReducer:

const formReducer = (state, action) => {
  if (action.type === FORM_INPUT_UPDATE) {
    const updatedValues = {
      ...state.inputValues,
      [action.input]: action.value
    };
    const updatedValidities = {
      ...state.inputValidities,
      [action.input]: action.isValid
    };
    let updatedFormIsValid = true;
    for (const key in updatedValidities) {
      updatedFormIsValid = updatedFormIsValid && updatedValidities[key];
    }
    return {
      formIsValid: updatedFormIsValid,
      inputValidities: updatedValidities,
      inputValues: updatedValues
    }
  }
  return state
}

This handler deals with both the text fields:

  const inputChangeHandler = useCallback(
    (inputIdentifier, inputValue, inputValidity) => {
      dispatchFormState({
        type: FORM_INPUT_UPDATE,
        value: inputValue,
        isValid: inputValidity,
        input: inputIdentifier
      })
    },
    [dispatchFormState]
  )

This handler deals with the login button:

  const authHandler = async () => {
    let action
      action = authActions.login(
        formState.inputValues.username,
        formState.inputValues.password
      )
    setError(null)
    setIsLoading(true)
    try {
      await dispatch(action)
      setIsLoading(false)
      props.navigation.navigate('App')
    } catch (err) {
      setError(err.message)
      setIsLoading(false)
    }
  }

The problem I'm having is that when the authHandler is called only the username is set and not the password. The password gets set after the login call. If I click the login button a second time it works correctly.

How do I make sure that the password event completes before the button press starts?


JSON Parse error: Unexpected EOF in React Native Expo

$
0
0

I'm getting JSON Parse error: Unexpected EOF in Expo app.
I'm not sure why this issue occurred.

    export const serviceCaller = <TResp>(url: string, request: HttpRequest): Promise<TResp> => {
    return new Promise<TResp>(async (resolve) => {
            try {
            const response = await fetch(url, request);
            const json: TResp = await response.json();
                resolve(json);
            } catch (error) {
               console.log(error);
               resolve(null);
           }
        });
    };

Error list:

  • JSON Parse error: Unexpected EOF
  • node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
  • node_modules\promise\setimmediate\core.js:123:25 in
  • ... 8 more stack frames from framework internals

push in typescript of react native

$
0
0

I am studying typescript in react native.

If I typed the following code as vanilla javascript, the app works well. But typed as a typescript, I received a message circleStyles.push(styles.circleCorrect); is an error. I understand it seems like the problem of type but I do not get how to solve it.

Does anyone have an idea?

import React from "react";
import { View, StyleSheet, Dimensions, Image } from "react-native";

const screen = Dimensions.get("window");

const styles = StyleSheet.create({
  container: {
    position: "absolute",
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  circle: {
    backgroundColor: "#ff4136",
    width: screen.width / 2,
    height: screen.width / 2,
    borderRadius: screen.width / 2,
    alignItems: "center",
    justifyContent: "center"
  },
  circleCorrect: {
    backgroundColor: "#28A125"
  },
  icon: {
    width: screen.width / 3
  }
});

export const Alert = ({ correct, visible }) => {
  if (!visible) return null;

  const icon = correct
    ? require("../assets/check.png")
    : require("../assets/close.png");

    const circleStyles = [styles.circle];

    if (correct) {
      **circleStyles.push(styles.circleCorrect);**
    }

  return (
    <View style={styles.container}>
      <View style={circleStyles}>
        <Image source={icon} style={styles.icon} resizeMode="contain" />
      </View>
    </View>
  )
}

React Native 0.61.0+ : How to add constructor in App.js file

$
0
0

How to add constructor(props){} or change App.js in react native 0.61.4 +

My app app.js is:

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$Node = () => {
  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;

Use undefined instead of null in RealmJS

$
0
0

I am wondering if there is a way to force RealmJS return undefined instead of null on optional fields?

I am asking this, because typescript's optional types is actually T | undefined, not T | null. I don't want to mix up undefined and null.

Thank you.

React Native unable to resolve module from file

$
0
0

I'm trying to store all the CSS style values into one single ts file: styles/base.ts, and export those values in styles/index.ts file.
But when I try to use import the value from index.ts in my App.tsx file, it says

Unable to resolve module "styles/index" from "App.tsx": "styles/index" could not be found within the project.`.

I'm not sure is it a correct way to manage the styles inside application. Can anyone help me?

Here is how my base.ts file looks like:

export const colors = {
  grey: "#E3E1D6",
  black: "#333333",
};

index.ts:

import * as BaseStyle from "./base";
export {BaseStyle};

App.tsx:

import React from "react";
import {StyleSheet, View, Text} from "react-native";
import {BaseStyle} from "styles/index";
const App = () => {
  return (
    <>
      <View style={styles.body}>
        <Text>Test</Text>
      </View>
    </>
  );
};
const styles = StyleSheet.create({
  body: {
    backgroundColor: BaseStyle.colors.grey,
  },
});
export default App;

And here is my package.json looks like:

{
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.4"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "@types/jest": "^24.0.18",
    "@types/react-native": "^0.60.22",
    "@types/react-test-renderer": "16.9.0",
    "babel-jest": "^24.9.0",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0",
    "typescript": "^3.6.3"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

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.

Must use destructuring props assignment issue

$
0
0

I was making an app in react-native and when I try to put on text one of the values of props, I get an error message like this: Must use destructuring props assignment

The code is this:

<Text style={styles.SubTextButton}>
      {props.date1} - {props.date2}
</Text>

and the props look like this:

(props: {
  text: string
  date1: string
  date2: string
})

The thing is, this actually don't ruin my app and all work well. But I would like to know if it is maybe a question of format in the writing of the code or even an error of the ESlinter.


How to hide a hyperlink available in antd table column?

$
0
0

I am using Antd Editable Rows table in typescript(Ref:https://beta.ant.design/components/table/#components-table-demo-edit-row) I have included checkbox column as well for the table. Now my requirement is, if any one of the checkbox is checked, then Edit hyperlink( tag with id ='anchorEdit') will be enabled. If more than one checkbox is checked, then Edit hyperlink will be disabled/ hidden. Code to display the Edit hyperlink is as below:

this.columns = [{
  title: 'name',
  dataIndex: 'name',
  width: '25%',

}, {
  title: 'age',
  dataIndex: 'age',
  width: '15%',

}, {
  title: 'address',
  dataIndex: 'address',
  width: '40%',

}, {
      title: 'operation',
      dataIndex: 'operation',
      render: (text, record) => {
        //let anchorID = 'anchorEdit'+record.ID;
        const { editingKey } = this.state;
        const editable = this.isEditing(record);
        return editable ? (
          <span>
             <EditableContext.Consumer>
              {form => (
                <a
                  onClick={() => this.save(form, record.ID)}
                  style={{ marginRight: 8 }}
                >
                  Save
                </a>
              )}
            </EditableContext.Consumer> 
            <Popconfirm title="Sure to cancel?" onConfirm={() => this.cancel(record.ID)}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (<a className='display' id='anchorEdit' onClick={() => this.edit(record.ID)}>Edit</a>);
    );
  },
}];

please help to do the changes? Thanks in Advance!

React-Native Icon at createBottomTabNavigator does not appear

$
0
0

I am fairly new to React-Native and I am trying to implement a bottom navigation bar.

I have succeeded to do this, however, I can not seem to get the Icons working.

Code that I am using

import React from 'react';

import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {NewsPage} from "./src/components/NewsPage";
import {TaskOverview} from "./src/components/TaskOverview";
import {Agenda} from "./src/components/Agenda";
import {Wiki} from "./src/components/Wiki";
import {Profile} from "./src/components/Profile";
import {Icon} from 'react-native-elements'

const TabNavigator = createBottomTabNavigator({
    TaskOverview: {
        screen: TaskOverview,
        navigationOptions: {
            tabBarLabel: 'Example title',
            tabBarIcon: ({tintColor}) => (
                <Icon name="rocket" color={tintColor} size={24}/>
            )
        },
    },
    NewsPage: {
        screen: NewsPage,
        navigationOptions: {
            tabBarLabel: 'Example title2',
            tabBarIcon: ({tintColor}) => (
                <Icon name="rocket" color={tintColor} size={24}/>
            )
        },
    },
});

const AppContainer = createAppContainer(TabNavigator);

export default class App extends React.Component {
    render() {
        return <AppContainer/>;
    }
}

Result that I am getting

It shows me bottom navigation but for the icon, it literally shows me a question mark.

What have I tried

  • Instead of Icon, I have tried working with IonIcon, but this did not solve this issue for me.
  • I tried different Icon names.

I hope someone can give me some insight.

Typescript How to define a property type as type of type?

$
0
0

So I'm struggling a little to work this out or find out if it's even possible,

So I'm trying to create a set of Types that are to be used in a React Native App, but this question relates to Typescript.

So I'm having a problem of: in my code I have changeMainComponent(Component: SomeType): void; Where some type is currently incorrectly as ComponentViewInterface<P,S,SS> what I actually need is for Component to be a Class that implements ComponentViewInterface<P,S,SS>

I have tried to use typeof ComponentViewInterface<P,S,SS>; as the type but that gives me an error saying 'ComponentViewInterface' only refers to a type, but is being used as a value here.

The Code below is to show my full use case if needed

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

export interface ComponentViewInterface<ComponentPropertes, S, SS> extends React.Component<ComponentPropertes, S, SS>{

}

export interface ComponentAppInterface<P={},S={}, SS={}> extends React.Component<P,S,SS>{
    changeMainComponent(Component: ComponentViewInterface<P,S,SS>): void;
}


export default interface ComponentPropertes<P={}, S={}, SS={}>{
    app:{
        Width: number;
        Height: number;
    }
    Frame: ComponentAppInterface<P, S, SS>;
}

export function CreateDefaultProperties<P, S, SS>(Component: ComponentAppInterface<P, S, SS>): ComponentPropertes<P, S, SS>{
    let ret:ComponentPropertes<P, S, SS> = {
        app:{
            Width: Dimensions.get('window').width,
            Height: Dimensions.get('window').height,
        },
        Frame: Component
    }
    return ret;
}

App.tsx (app entry point)

import React from 'react';
import { ComponentAppInterface, CreateDefaultProperties } from './src/interface/AppProps';
import {View, Button, Text} from 'react-native';
import WelcomeScreen from './src/Screens/WelcomeScreen'

export default class TestApp extends React.Component<{},{},any> implements ComponentAppInterface<{},{},any>{
    public changeMainComponent(component: any){
        this.setState({MainComponent:component});
    }

    public state = {
        MainComponent: WelcomeScreen
    }

    public render(){
        return (<View>
            <this.state.MainComponent {...CreateDefaultProperties(this)}/>
        </View>)
    }
}

WelcomeScreen.tsx

import React from 'react';
import { ComponentAppInterface, CreateDefaultProperties, ComponentViewInterface } from './src/interface/AppProps';
import {View, Button, Text} from 'react-native';
import WelcomeScreen from './src/Screens/WelcomeScreen'

export default class TestApp extends React.Component<{},{},any> implements ComponentAppInterface<{},{},any>{
    public changeMainComponent(component: ComponentViewInterface<{},{},any>){
        this.setState({MainComponent:component});
    }

    public state = {
        MainComponent: WelcomeScreen
    }

    public render(){
        return (<View>
            <this.state.MainComponent {...CreateDefaultProperties(this)}/>
        </View>)
    }
}

React Native Performance: Javascript vs Typescript

$
0
0

Is Javascript or Typescript different in React Native App performance?

Which Javascript or Typescript is recommended for developing React Native application?

I hope my question wasn't too imaginative.

Jest test failing for DrawerNavigator in a Typescript React native project

$
0
0

I'm new at React Native and Typescript. I have been implementing a small project with Stack Navigation and Drawer Navigation. The project has been working well but now I have to make some unit tests. I started with a very simple one but is failing :/

This is the code for the navigation of the app:

Navigator.tsx

import App from "../../App";
import React from 'react';
import { Image, StyleSheet, TouchableHighlight } from 'react-native';
import { createAppContainer, NavigationScreenProp, NavigationState, NavigationParams } from 'react-navigation';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { createStackNavigator } from 'react-navigation-stack';
import LoginScreen from "./LoginScreen";
import RegisterScreen from "./RegisterScreen";
import MapScreen from "./MapScreen";
import BikesScreen from "./BikesScreen";
import TheftScreen from "./TheftScreen";
import RentBikeScreen from "./RentBikeScreen";
import RouteListScreen from "./RouteListScreen";
import CouponScreen from "./CouponScreen";
import strings from "../config/strings";

interface Props {
  navigation: NavigationScreenProp<NavigationState,NavigationParams>;
}

interface State {}

export default class NavigatorContainer extends React.Component<Props, State> {  
  render() {

  const DrawerStack = 
  createDrawerNavigator({     
    Map: MapScreen,      
    Bikes: BikesScreen,  
    Theft: TheftScreen,
    RouteList: RouteListScreen,
    Coupon: CouponScreen   
  })


  DrawerStack.navigationOptions = ({ navigation }) => {
    const { routeName } = navigation.state.routes[navigation.state.index];

    const headerTitle = 
    routeName == "Map" ? strings.CONSULT_ROUTE : 
    routeName == "Bikes" ? strings.BIKES_TITLE : 
    routeName == "Theft" ? strings.THEFT_REPORT_TITLE :
    routeName == "Register" ? strings.REGISTER_SCREEN_TITLE :
    routeName == "RouteList" ? strings.ROUTE_LIST_TITLE :
    routeName == "Coupon" ? strings.COUPON_TITLE : "";

    return {
      headerTitle,
      headerLeft: ({ tintColor }: {tintColor: any}) => (
        <TouchableHighlight onPress={() => navigation.toggleDrawer()}><Image
          source={require('../assets/images/drawer.png')}
          style={[styles.icon, { tintColor: tintColor }]}        
        /></TouchableHighlight>)
    };
  };

  const AppNavigator = createStackNavigator(
    {        
      Login: {
        screen: LoginScreen,
        navigationOptions: {
          header: null 
        }      
      },   
      Register: {
        screen: RegisterScreen    
      },      
      DrawerStack: DrawerStack
    },
    {
      initialRouteName: 'Login',
    }
  );

  const AppContainer = createAppContainer(AppNavigator);
    return <AppContainer />;   
  }
}

const styles = StyleSheet.create({
  icon: {
    width: 24,
    height: 24,
  },
});

This is the test:

App-test.tsx

/**
 * @format
 */
import 'react-native';
import React from 'react';
import App from '../App';

import * as renderer from 'react-test-renderer';

jest.mock('react-native', () => {
  return { 
    StyleSheet: {
      create: () => {

      }
    },
    Platform: {}
  }
});

it('renders correctly', () => {
  renderer.create(<App />);
});

When executing the tests with "yarn test" I get this:

src/screens/Navigator.tsx:50:38 - error TS7031: Binding element 'navigation' implicitly has an 'any' type

So I changed 'navigation' with 'navigation : NavigationScreenProp':

DrawerStack.navigationOptions = (navigation : NavigationScreenProp<NavigationState,NavigationParams>) => {....

And the test pass!... but now when I try to go to one of the screens of the DrawerNavigator for instance MapScreen, using 'this.props.navigation.navigate('Map')' I get the error:

TypeError: undefined is not an object (evaluating 'navigation.state.routes')

I see that the problem is in this line:

const { routeName } = navigation.state.routes[navigation.state.index];

but I don't know how to solve it and don't understand why it worked only with '({ navigation })'

Any ideas?

Typescript error trying to convert react-native flow project to typescript

$
0
0

Relatively new with react-native...

Trying conversion of a react-native flow project to react-native typescript project. Managed to work out other compile errors, but was getting the following:

Line:

import { ____ViewStyleProp_Internal as Style } from "react-native/Libraries/StyleSheet/StyleSheetTypes";

Error:

Cannot find module 'react-native/Libraries/StyleSheet/StyleSheetTypes'.ts(2307)

It doesn't seem to be finding the Libraries folder under react-native...(?) My installation of react-native under AppData\Roaming\npm\node_modules\react-native-cli\node_modules doesn't have Libraries folder... where is Libraries folder located?

Current package.json:

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "autobind-decorator": "^2.4.0",
    "expo": "^35.0.0",
    "native-base": "^2.13.8",
    "react": "16.8.3",
    "react-dom": "16.8.3",
    "react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",
    "react-native-web": "^0.11.7",
    "react-navigation": "^4.0.10"
  },
  "devDependencies": {
    "@types/react": "^16.8.23",
    "@types/react-native": "^0.57.65",
    "babel-preset-expo": "^7.1.0",
    "typescript": "^3.6.3"
  },
  "private": true
}

Thnks.

What is proper replacement for React.ChildrenArray in typescript?

$
0
0

Why does the following react-native code give typescript error?

type ContainerProps = BaseProps & {
    children: React.ChildrenArray<React.ReactElement<any>>;
    withGutter?: boolean;
};

any Namespace 'React' has no exported member 'ChildrenArray'.ts(2694)

What is the correct expression instead? This was originally flow based js code being converted to typescript...


Using TouchableOpacity with primary transparent gives typescript error

$
0
0

Below is the Code what i am trying to execute using typescript and react-native and it gives me typescript error in VSCODE IDE

import { TouchableOpacity } from "react-native";

<TouchableOpacity
    primary
    transparent
    onPress={this.send}
>
    <Text style={styles.btnText}>Send</Text>
</TouchableOpacity>

gives following typescript error in VSCode:

(alias) class TouchableOpacity
import TouchableOpacity
No overload matches this call.

Overload 1 of 2, '(props: Readonly<TouchableOpacityProps>): TouchableOpacity', gave the following error.

Type '{ children: Element; primary: true; transparent: true; onPress: () => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<{ children?: ReactNode; }>'.

Property 'primary' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<{ children?: ReactNode; }>'.

Overload 2 of 2, '(props: TouchableOpacityProps, context?: any): TouchableOpacity', gave the following error.

Type '{ children: Element; primary: true; transparent: true; onPress: () => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<{ children?: ReactNode; }>'.

Property 'primary' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<{ children?: ReactNode; }>'.ts(2769)

No overload matches this call in React Native

$
0
0

I want to separate the styles for elements to make them easier to read. I wrote next code

let styles={
    search:{
        container:{
            position:"absolute",
            top:0,
        },
    }
}

And then use as

<View style={styles.search.container}/>

Everything work fine but TypeScript throw error for style - 'No overload matches this call'

Tell me please how to suppress this error?

How do I create typescript type definitions for react-native native ui component?

$
0
0

Let us say that I have a react native native UI component like the one in this example. How do I create a typescript type definition for it, like the ones that can be imported, for example with 'npm i @types/somelib'? I didn't find explanations about how to do this in the documentation.

The idea is to be able to use the native component seamlessly in a react-native typescript project and for that I need to create the type definition for native components. So, how do I create typescript type definitions for native components?

Error in jest test: TypeError: Cannot read property 'container' of undefined

$
0
0

I'm trying to test a typescript react-native class using jest but the test is not passing.

This is the class:

import * as React from "react";
import {
  Image,
  KeyboardAvoidingView,
  StyleSheet,
  View
} from "react-native";
import colors from "../config/colors";
import constants from "../config/constants";
import App from "../../App";

interface Props {
  ...
}

interface State {
...
}

class LoginScreen extends React.Component<Props, State> {
 .
 .
 .  
  render() {

    return (
      <KeyboardAvoidingView
        style={styles.container}   
        behavior={constants.IS_IOS ? "padding" : undefined}>
        .
        .
        .
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({  
  container: {
    flex: 1,
    backgroundColor: colors.WHITE,
    alignItems: "center",
    justifyContent: "space-between"
  }
});

export default LoginScreen

but I'm getting the error:

TypeError: Cannot read property 'container' of undefined

       98 |     return (
       99 |       <KeyboardAvoidingView
    > 100 |         style={styles.container}   
          |                       ^
      101 |         behavior={constants.IS_IOS ? "padding" : undefined}>

The test is this one:

/**
 * @format
 */

import 'react-native';
import React from 'react';
import LoginScreen from '../src/screens/LoginScreen';

// Note: test renderer must be required after react-native.
import * as renderer from 'react-test-renderer';

jest.mock('react-native', () => {
  return { 
    StyleSheet: {
      create: jest.fn()         
    },
    .
    .
    .
  }
});

const createTestProps = (props: Object) => ({
    .
    .
    ...props
  });
  let props = createTestProps({});
it('renders correctly', () => {
    const tree = renderer.create(<LoginScreen {...props}/>).toJSON();
    expect(tree).toMatchSnapshot();
});

As you can see the problem is here:

style={styles.container} 

the method create from the StyleSheet mock returns undefined so when container is called the error happens. How can I fix this?

Unexpected behaviour of rootDir and outDir

$
0
0

I am trying to use TypeScript with React Native.

This is my tsconfig.json:

{
    "compilerOptions": {
        "target": "es2015",
        "module": "es2015",
        "jsx": "react",
        "outDir": "build",
        "rootDir": "src",
        "allowSyntheticDefaultImports": true,
        "noImplicitAny": true,
        "experimentalDecorators": true,
        "preserveConstEnums": true,
        "allowJs": true,
        "sourceMap": true
    },
    "filesGlob": [
        "typings/index.d.ts",
        "src/**/*.ts",
        "src/**/*.tsx"
    ],
    "exclude": [
        "index.android.js",
        "index.ios.js",
        "build",
        "node_modules"
    ],
    "compileOnSave": false
}

I would like all .ts(x) files in the src directory to be compiled to the build directory.

Expected:

MyAwesomeReactNativeApp/
├── src/
│   └── index.tsx
└── build/
    └── index.js

Got:

MyAwesomeReactNativeApp/
├── src/
│   └── index.tsx
└── build/
    ├── src/
    │   └── index.js
    ├── index.android.js
    ├── index.ios.js
    └── __tests__/

The compiler complains:

error TS6059: File '[...]/__tests__/index.android.js' is not under 'rootDir''[...]/src'. 'rootDir' is expected to contain all source files.
error TS6059: File '[...]/__tests__/index.ios.js' is not under 'rootDir''[...]/src'. 'rootDir' is expected to contain all source files.
error TS6059: File '[...]/index.android.js' is not under 'rootDir''[...]/src'. 'rootDir' is expected to contain all source files.
error TS6059: File '[...]/index.ios.js' is not under 'rootDir''[...]/src'. 'rootDir' is expected to contain all source files.

What am I doing wrong here?

Thank you in advance!

Viewing all 6406 articles
Browse latest View live


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