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

React/React Native + Typescript Error: Cannot find name 'INSERT FUNCTION NAME HERE'

$
0
0

I'm just diving into Typescript and trying to implement it into one of my projects. However, I'm getting an error Cannot find name 'selectValue' when hovering over the selectValue method (See image below). Am I missing something in my tsconfig.json??

tsconfig.json:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["es6"],                           /* Specify library files to be included in the compilation. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "react-native",                    /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "removeComments": true,                /* Do not emit comments to output. */
    "noEmit": true,                           /* Do not emit outputs. */
    "incremental": true,                      /* Enable incremental compilation */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    "isolatedModules": true,                  /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    "strictFunctionTypes": true,              /* Enable strict checking of function types. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": "./",                          /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    "typeRoots": [                            /* List of folders to include type definitions from. */

    ],
    "types": [                                /* Type declaration files to be included in compilation. */
      "react",
      "react-native"
    ],
    "allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

Component:

// Imports: Dependencies
import React, { useState } from 'react';
import { Dimensions, Platform, Picker, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
// import DateTimePicker from '@react-native-community/datetimepicker';
import Modal from 'react-native-modal';
import Icon from 'react-native-vector-icons/Ionicons';
Icon.loadFont();

// Screen Dimensions
const { height, width } = Dimensions.get('window');

// Component: List Picker
export const ListPicker = (props: object) => {
  // React Hooks: State
  const [ modalVisible, toggle ] = useState(false);
  const [ value, setValue ] = useState();

  // React Hooks: Lifecycle Methods

  // Toggle Modal
  toggleModal = () => {
    try {
      // Check Platform (iOS)
      if (Platform.OS === 'ios') {
        // React Hook: Toggle Modal
        toggle((modalVisible) => !modalVisible);
      }

      // Check Platform (Android)
      if (Platform.OS === 'android') {

      };
    }
    catch (error) {
      console.log(error);
    }
  };

  // Select Value
  selectValue = (value: string) => {
    try {
      // React Hook: Set Value
      setValue(value);

      // React Props: onValueChange
      props.onValueChange(value);
    }
    catch (error) {
      console.log(error);
    }
  };

  // Render Picker
  renderPicker = () => {
    try {
      return (
        <Picker
          selectedValue={value}
          onValueChange={this.selectValue}>
          {props.items.map((item: object) => {
            return (
              <Picker.Item
                label={item.label}
                value={item.value}
                key={item.key || item.label}
                color={item.color}
              />
            );
          })}
        </Picker>
      )
    }
    catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.inputTitleContainer}>
      <Text style={styles.inputTitle}>{props.title}</Text>
      </View>

      <TouchableOpacity onPress={this.toggleModal} style={styles.fieldTextContainer}>
        <Text style={styles.fieldText} numberOfLines={1}>{value !== undefined ? value : 'Select'}</Text>

        <Icon name="ios-arrow-forward" size={22} style={styles.arrowForward}/>
      </TouchableOpacity>

      <Modal isVisible={modalVisible} style={styles.modal}>
        <View style={styles.modalContainer}>
          <View style={styles.pickerHeaderContainer}>
            <TouchableOpacity onPress={this.toggleModal} >
              <Text style={styles.doneText}>Done</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.pickerContainer}>
            {this.renderPicker()}
          </View>
        </View>
      </Modal>
    </View>
  );
}

// Styles
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    width: width - 32,
    marginLeft: 16,
    marginRight: 16,
    justifyContent: 'center',
  },
  modal: {
    margin: 0,
  },
  modalContainer: {
    height: '100%',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
  pickerHeaderContainer: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    height: 40,
    width: width,
    backgroundColor: '#FAFAF8',
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  pickerContainer: {
    height: 220,
    width: width,
    // backgroundColor: '#CFD3D9',
    backgroundColor: 'white',
  },
  doneText: {
    fontFamily: 'System',
    color: '#007AFF',
    fontWeight: '600',
    fontSize: 17,
    marginRight: 16,
  },
  stateContainer: {
    alignItems: 'center',
    width: 75,
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  inputTitleContainer: {
    width: 75,
    marginBottom: 4,
  },
  inputTitle: {
    color: '#7D7D7D',
    borderColor: '#7D7D7D',
    fontSize: 10,
    fontWeight: '600',
    textTransform: 'uppercase',
  },
  fieldTextContainer: {
    height: 40,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,    
  },
  fieldText: {
    width: width - 32 - 20,
    fontFamily: 'System',
    fontSize: 17,
    fontWeight: '400',
    color: '#000000',
    alignSelf: 'center',
  },
  arrowForward: {
    color: 'black',
    opacity: .3,
    marginRight: 7,
  },
});

Screenshot:

enter image description here


How To Publish My First React Native Component Library?

$
0
0

I was in the process of trying to find the right components and a full component library at that, but I was coming up short and built my own.

I noticed NPM libraries don't have any React Native, iOS, Android, app.json, and etc. files. Should I add these to my .gitignore and then they won't be published with my NPM package? I've built it on a React Native app, but from my understanding, so there should only be the following files listed below:

  • A src folder containing the components ("main" : "./src/index.tsx" is in the package.json file)
  • README.md
  • package.json
  • tsconfig.json (I used TypeScript, so is this file necessary?)

As of right now, my react-native-ultimate-modal-picker package is 636 MB and 19389 total files. Again, this is my first time publishing a package, so I just need some clarification.

I've used npm publish to do the initial publish and will do another publish once I trim everything down correctly.

React Native with typescript unable to resolve modules

$
0
0

This is embarrassing, but I don't know what else to do. I wanted to port my little React Native project to TypeScript, so I created an empty React Native project with TypeScript template, tweaked tsconfig.json to use custom paths such as @app and I tried to run it. It didn't. And this was yesterday, I did some googling, but those who had the same issue suggested to clean the packager, remove node_modules and reinstall packages all over, for example, this one, so I did, and it didn't work.

These are my steps for reinstalling react-native-cli (at first I thought that the problem is with outdated package, it wasn't):

  • npm uninstall -g react-native-cli
  • yarn global add @react-native-community/cli

Those below I followed already that many times, that I don't remember the exact number:

  • npx react-native init MyApp --template react-native-template-typescript
  • yarn add redux redux-logger redux-thunk react-redux
  • yarn add --dev @types/react @types/react-redux @types/redux-logger

And then making changes to tsconfig.json, so it looks likes this ( my changes marked with ->):

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "esnext",                       /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["dom", "esnext"],                 /* Specify library files to be included in the compilation. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    "jsx": "react-native",                    /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "noEmit": true,                           /* Do not emit outputs. */
    "incremental": true,                      /* Enable incremental compilation */
    "isolatedModules": true,                  /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */

    /* Module Resolution Options */
    "moduleResolution": "node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
->  "baseUrl": "./src",                       /* Base directory to resolve non-absolute module names. */
->  "paths": {                                /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
->    "@app/*": ["./*"]
->  },
    "allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */    
  },
  "exclude": [
    "node_modules", "babel.config.js", "metro.config.js", "jest.config.js"
  ]
}

My project structure looks like this:

MyApp
├── ios
├── android
├── src
│   ├── index.tsx
│   ├── constants
│   │   └── app.json
│   ├── support   
│   │   └── store.tsx   
│   └── reducers   
│       └── index.tsx
├── tsconfig.json
├── package.json
├── index.js 
└── [ the rest ]

And when I'm trying to import {initStore} from '@app/support/store' in MyApp/src/index.tsx the Metro gives me the following:

Loading dependency graph, done.
error: bundling failed: Error: Unable to resolve module `@app/support/store` from `src/index.tsx`: @app/support/store could not be found within the project.

Then I tried cleaning with following commands, but it also didn't do any good:

  • watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache

But, what interesting, after that I tweaked tsconfig.json, Atom doesn't complain about paths like @app/support/store, it even provides autocompletion, it recognizes @app/support/ as directory and @app/support/store as a script, so I assume tsconfig.json is not the problem.

TypeScript Error: How do I correctly add Interface to promise returned?

$
0
0

I'm working on my first TypeScript project and I'm having trouble add types correctly to my code. From the React Native Docs, DatePickerAndroid "returns a Promise which will be invoked an object containing action, year, month (0-11), day if the user picked a date.

For this next part, I've added "?" and undefined in the interface. "If the user dismissed the dialog, the Promise will still be resolved with action being DatePickerAndroid.dismissedAction and all the other keys being undefined."

I've tried several ways, but how can I correctly apply types to DatePickerAndroid?

Error:

src/DatePicker.tsx:47:15 - error TS2322: Type 'DatePickerAndroidOpenReturn' is not assignable to type 'Props'.
  Type 'DatePickerAndroidDateSetAction' is missing the following properties from type 'Props': title, onValueChange, mode, date47

const { action, year, month, day } : Props = await DatePickerAndroid.open({

Interface:

// TypeScript: Types
interface Props {
  title: string,
  onValueChange: Function,
  mode: 'calendar' | 'spinner' | 'default' | undefined,
  action: 'dateSetAction' | 'dismissedAction',
  date: Date | undefined,
  minDate?: Date | undefined,
  maxDate?: Date | undefined,
  year?: number | Date,
  month?: number | Date,
  day?: number | Date,
}

DatePicker.tsx

  const toggleModal = async (props: Props) => {
    try {
      // Check Platform (iOS)
      if (Platform.OS === 'ios') {
        // React Hook: Toggle Modal
        toggle((modalVisible) => !modalVisible);
      }

      // Check Platform (Android)
      if (Platform.OS === 'android') {
        const { action, year, month, day } : Props = await DatePickerAndroid.open({
          date: date,
          mode: props.mode,
        });

        // Action: Date Set
        if (action === DatePickerAndroid.dateSetAction) {
          // New Date
          let newDate:Date = new Date(year, month, day);

          // Select Date
          selectDate(newDate);
        }

        // Action: Dismissed
        if (action === DatePickerAndroid.dismissedAction) {
          // Do Nothing
        }
      };
    }
    catch (error) {
      console.log(error);
    }
  };

React Native Typescript: Type 'string' is not assignable to type '"solid" | "clear" | "outline"'.ts(2322)

$
0
0

I am using TypeScript alongside with React Native.

import React from 'react';
import { Button } from 'react-native-elements';
import { IThemedButton } from '../../../models/themedButton';

interface IThemedButtonProps {
  data: IThemedButton;
}

const ThemedButton: React.FC<IThemedButtonProps> = ({
  data: { title, type, onPress },
}) => {
  return <Button title={title} type={type} onPress={onPress} />;
};

export default ThemedButton;

export interface IThemedButton {
  title: string;
  type: string;
  onPress: any;
}

I set type to string, because the button title is a string, but VS Code shows me an error:

Type 'string' is not assignable to type '"solid" | "clear" | "outline"'.ts(2322)
index.d.ts(326, 3): The expected type comes from property 'type' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>'

I read in the docs, that the type is optional: https://react-native-training.github.io/react-native-elements/docs/button.html#type

What can be the solution?

Javascript Library with typings is Not a Module (React Native)

$
0
0

I'm trying to integrate a Javascript Library (Microsoft Playfab) into my React Native app as per recommended here. The library comes with typings and has the structure as shown here. I have a file playfabWrapper.ts with the following.

/// <reference path="../../node_modules/playfab-web-sdk/src/Typings/PlayFab/PlayfabClientApi.d.ts" />

import Playfab from 'playfab-web-sdk/src/PlayFab/PlayFabClientApi.js';

function test(titleId: string, customId: string/*, success: (data: PlayFabClientModels.LoginResult) => void, error: (message: string) => void*/): void {
    Playfab.ClientApi.LoginWithCustomID({
        TitleId: titleId,
        CustomId: customId,
        CreateAccount: true,
    }, (result: any, problem: any) => {
        ...
    });
}

This gives me the error

Could not find a declaration file for module 'playfab-web-sdk/src/PlayFab/PlayFabClientApi.js'. '/Users/../project/node_modules/playfab-web-sdk/src/PlayFab/PlayFabClientApi.js' implicitly has an 'any' type.
Try `npm install @types/playfab-web-sdk` if it exists or add a new declaration (.d.ts) file containing `declare module 'playfab-web-sdk/src/PlayFab/PlayFabClientApi.js';`

Then I tried copying the typings from Typings/Playfab and pasting them in the same location as PlayFabClientApi.js. This gives me the following error.

File '/Users/../project/node_modules/playfab-web-sdk/src/PlayFab/PlayFabClientApi.d.ts' is not a module.

Interestingly, if I delete the import line my IDE can detect Playfab correctly but it is always undefined. Am I missing something? Is this kind of library even possible to import? I notice it doesn't have an index.d.ts, could that contribute to the issue? Any help would be appreciated. Thanks.

How can I cache the getDownloadUrl() calls on the client with Firebase Firestore?

$
0
0

I store some Firebase Storage paths for images/videos in the backend DB and the mobile client uses these to fetch the download URLs as/when needed for my views:

import {firebase} from '@react-native-firebase/storage';

// e.g. 'images/stars.jpg'
const getDownloadUrlForFilePath = (filePath: string | null): Promise<string> => {
  if (filePath === null) {
    throw 'Path is null!';
  }
  return getDownloadUrlForRef(firebase.storage().ref(filePath));
};

const getDownloadUrlForRef = (ref): Promise<string> => {
  return ref.getDownloadURL();
};

The problem is that I need the same image at many places. Hence I frequently call getDownloadURL() to retrieve the very same download Url. This results in the handset making multiple http requests for the same resource as it appears when I debug the network traffic.

I am not storing the retrieved download URLs in the mobile client anywhere in my current implementation.

I would like to find a way for the app to fetch the download URL only once for the same path and cache it. Is this supported by the Firebase SDK?

JSX Element Type Error: Adding Types to object returned from .map function

$
0
0

I'm trying to add the itemtype to the object that is returned from the .map function. However, I'm getting a JSX error and I tried adding item: JSX.Element to the Item type, but that doesn't seem to work correctly. Can someone clarify this for me? Below is the error, types, and code.

Error:

src/ListPicker.tsx:69:28 - error TS2345: Argument of type '(item: Item) => JSX.Element' is not assignable to parameter of type '(value: string, index: number, array: string[]) => Element'.
  Types of parameters 'item' and 'value' are incompatible.
    Type 'string' is not assignable to type 'Item'.

      {props.items.map((item: Item) => {
                              ~~~~~~~~~~~~~~~~~

Types:

// TypeScript: Types
interface Props {
  title: string,
  items: Array<string>,
  onPress: Function,
  onValueChange: Function,
}

interface Item {
  label: string,
  value: string,
  key: number | string,
  color: string,
};

ListPicker.tsx:

// Render iOS Picker
  const renderIOSPicker = () => {
    try {
      return (
        <Picker
          selectedValue={value}
          onValueChange={selectValue}>
          {props.items.map((item: Item) => {
            return (
              <Picker.Item
                label={item.label}
                value={item.value}
                key={item.key || item.label}
                color={item.color}
              />
            );
          })}
        </Picker>
      )
    }
    catch (error) {
      console.log(error);
    }
  };

Typescript onPress With Promise Returned Error

$
0
0

I'm implementing typescript into my project for the first time and I have an error coming from onPress which calls toggleModal. The error is coming from onPress

According to the React Native docs, DatePickerAndroid.open() does the following:

Returns a Promise which will be invoked an object containing action, year, month (0-11), day if the user picked a date. If the user dismissed the dialog, the Promise will still be resolved with action being DatePickerAndroid.dismissedAction and all the other keys being undefined.

Can someone clarify if the error is coming from the following and how to fix it?

  • The promise DatePickerAndroid.open() since it the response may or may not be returned
  • Do I need to type onPress as a function with onPress: Function?

Error

src/DatePicker.tsx:109:25 - error TS2769: No overload matches this call.
  Overload 1 of 2, '(props: Readonly<TouchableOpacityProps>): TouchableOpacity', gave the following error.
    Type '(props: Props) => Promise<void>' is not assignable to type '(event: GestureResponderEvent) => void'.
      Types of parameters 'props' and 'event' are incompatible.
        Type 'GestureResponderEvent' is missing the following properties from type 'Props': title, onPress, onValueChange, mode
  Overload 2 of 2, '(props: TouchableOpacityProps, context?: any): TouchableOpacity', gave the following error.
    Type '(props: Props) => Promise<void>' is not assignable to type '(event: GestureResponderEvent) => void'.

109       <TouchableOpacity onPress={toggleModal} style={styles.fieldTextContainer}>

Types

// TypeScript: Types
interface Props {
  title: string,
  onPress: Function,
  onValueChange: Function,
  mode: 'calendar' | 'spinner' | 'default',
  minDate?: Date | number;
  maxDate?: Date | number;
}

interface AndroidProps {
  action: 'dateSetAction' | 'dismissedAction',
  newDate?: Date;
  year?: number;
  month?: number;
  day?: number;
}

toggleModal

// Toggle Modal
  const toggleModal = async (props: Props) => {
    try {
      // Check Platform (iOS)
      if (Platform.OS === 'ios') {
        // React Hook: Toggle Modal
        toggle((modalVisible) => !modalVisible);
      }

      // Check Platform (Android)
      if (Platform.OS === 'android') {
        const { action, year, month, day } : AndroidProps = await DatePickerAndroid.open({
          date: date,
          mode: props.mode,
        });

        // Action: Date Set
        if (
           action === DatePickerAndroid.dateSetAction
           && year !== undefined
           && month !== undefined
           && day !== undefined
        ) {
          // New Date
          let newDate:Date = new Date(year, month, day);

          // Select Date
          selectDate(newDate);
        }

        // Action: Dismissed
        if (action === DatePickerAndroid.dismissedAction) {
          // Do Nothing
        }
      };
    }
    catch (error) {
      console.log(error);
    }
  };

DatePicker.tsx

<TouchableOpacity onPress={toggleModal} style={styles.fieldTextContainer}>
    <Text style={styles.fieldText} numberOfLines={1}>{date ? moment(date).format('MMM Do, YYYY') : 'Select'}</Text>

    <Icon name="ios-arrow-forward" size={22} style={styles.arrowForward}/>
  </TouchableOpacity>

TypeScript Error: Adding type to .map Array of Objects

$
0
0

I'm trying to add types to the Item object that is returned from unitedStates.map((item: Item) => {}, but I can't seem to correctly add the types.

I've defined the unitedStates array of objects as unitedStates: Array<UnitedStates> and that seems to be correct, but I'm not sure why Item is not correctly typed.

Error:

src/StatePicker.tsx:198:35 - error TS2345: Argument of type '(item: Item) => JSX.Element' is not assignable to parameter of type '(value: UnitedStates, index: number, array: UnitedStates[]) => Element'.
  Types of parameters 'item' and 'value' are incompatible.
    Type 'UnitedStates' is not assignable to type 'Item'.

                 {unitedStates.map((item: Item) => {

Types.tsx:

// TypeScript: Types
interface Props {
  title: string,
  onPress: Function,
  onValueChange: Function,
}

interface Item {
  label: string,
  value: string,
  key: number | string,
  color: string,
};

interface UnitedStates {
  label: string,
  value: string,
};

United States (Array of Objects):

// United States
  const unitedStates: Array<UnitedStates> = [
    { label: 'AL', value: 'AL' },
    { label: 'AK', value: 'AK' },
    { label: 'AZ', value: 'AZ' },
    { label: 'AR', value: 'AR' },
    { label: 'CA', value: 'CA' },
    { label: 'CO', value: 'CO' },
    { label: 'CT', value: 'CT' },
    { label: 'DE', value: 'DE' },
    { label: 'FL', value: 'FL' },
    { label: 'GA', value: 'GA' },
    { label: 'HI', value: 'HI' },
    { label: 'ID', value: 'ID' },
    { label: 'IL', value: 'IL' },
    { label: 'IN', value: 'IN' },
    { label: 'IN', value: 'IN' },
    { label: 'KS', value: 'KS' },
    { label: 'KY', value: 'KY' },
    { label: 'LA', value: 'LA' },
    { label: 'ME', value: 'ME' },
    { label: 'MD', value: 'MD' },
    { label: 'MA', value: 'MA' },
    { label: 'MI', value: 'MI' },
    { label: 'MN', value: 'MN' },
    { label: 'MS', value: 'MS' },
    { label: 'MO', value: 'MO' },
    { label: 'MT', value: 'MT' },
    { label: 'NE', value: 'NE' },
    { label: 'NV', value: 'NV' },
    { label: 'NH', value: 'NH' },
    { label: 'NJ', value: 'NJ' },
    { label: 'NM', value: 'NM' },
    { label: 'NY', value: 'NY' },
    { label: 'NC', value: 'NC' },
    { label: 'ND', value: 'ND' },
    { label: 'OH', value: 'OH' },
    { label: 'OK', value: 'OK' },
    { label: 'OR', value: 'OR' },
    { label: 'PA', value: 'PA' },
    { label: 'RI', value: 'RI' },
    { label: 'SC', value: 'SC' },
    { label: 'SD', value: 'SD' },
    { label: 'TN', value: 'TN' },
    { label: 'TX', value: 'TX' },
    { label: 'UT', value: 'UT' },
    { label: 'VT', value: 'VT' },
    { label: 'VA', value: 'VA' },
    { label: 'WA', value: 'WA' },
    { label: 'WV', value: 'WV' },
    { label: 'WI', value: 'WI' },
    { label: 'WY', value: 'WY' },
  ];

Render Method:

// Render iOS Picker
  const renderIOSPicker = () => {
    try {
      return (
        <Picker
          selectedValue={state}
          onValueChange={selectState}>
          {unitedStates.map((item: Item) => {
            return (
              <Picker.Item
                label={item.label}
                value={item.value}
                key={item.key || item.label}
                color={item.color}
              />
            );
          })}
        </Picker>
      )
    }
    catch (error) {
      console.log(error);
    }
  };

Issue with publishing my first NPM Package

$
0
0

I've created my first NPM package which is a React Native component library. I have have published it, but I can't seem to figure out what I'm doing wrong to get it working in my project.

package.json

I have the main, types (For Typescript), and files I included and used npm publish to save changes to NPM. Here's what my package.json has

"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": ["dist/", "package.json", "License.txt" ]

However, when I use npm i react-native-ultimate-modal-picker to install the package in my project, It's not working with my project and my package folder located in node_modules is outlined in red such as the following. What am I doing wrong??

enter image description here

Property 'map' does not exist on type 'MapView'

$
0
0

I am using typescript and react-native-maps to create a react-native application. I am following one of their examples given here.

Before I try to call the methods I have to create a ref as shown in the example but I am getting the following error.

"Property 'map' does not exist on type 'Map'"

Here's my code.

import React, { Component } from "react";
import MapView, { Marker } from "react-native-maps";

export default class Map extends Component {
  constructor(props: any) {
    super(props);

    this.state = {
      region: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA
      },
      coordinate: {
        latitude: LATITUDE,
        longitude: LONGITUDE
      }
    };
  }

  render() {
    return (
      <MapView
        // Getting that error in this line
        ref={map => { this.map = map; }}
        style={{ flex: 1 }}
        region={this.state["region"]}
      >
        <Marker coordinate={this.state["coordinate"]} />
      </MapView>
    );
  }
}

I tried some solutions that were given here but i suspect its not a solution for react-native?

Building React Native/Electron apps on remote server

$
0
0

Is there any standard way to build React Native (Android) / Electron (Win, Linux) apps on remote computer (server)?

By standard way I mean some tool what I can download and start some building server.

Or I need to make my own by for example making git, installing build-tools and programming some interface to build automatically.

I am not searching for 3th party cloud services.

Thanks for help, I not found any solution by searching on Google or here on SO.

ApolloClient Typescript Higher Order Component issue (not assignable to type)

$
0
0

I'm trying to create a HOC in a React Native app, but I'm having issues getting the definitions to work.

interface IWithApolloClientComponentProps {
    apolloClient: ApolloClient<any>;
}
export function withApolloClient<
    P extends IWithApolloClientComponentProps, 
    R = Omit<P, keyof IWithApolloClientComponentProps>
>(
    Component: React.ComponentType<P>
): React.ComponentType<R> {
        return function BoundComponent(props: R) {
            return <ApolloConsumer>{client => <Component {...props} apolloClient={client} />} . 
        </ApolloConsumer>;
    };
}

My VSCode keeps giving the following error:

Type 'R & { apolloClient: ApolloClient<object>; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
  Type 'R & { apolloClient: ApolloClient<object>; }' is not assignable to type 'P'.
'R & { apolloClient: ApolloClient<object>; }' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint 'IWithApolloClientComponentProps'.ts(2322)

Is anyone seeing something I'm doing terribly wrong here?

Publishing NPM Package Error "Can't find variable: React"

$
0
0

I've created my first NPM package which is a React Native component library. I have have published it, but I can't seem to figure out what I'm doing wrong to get it working in my project. I'm getting the error Can't find variable: React.

index.js (Am I correctly exporting my react native components here?)

// Exports: Components
export { DateRangePicker } from './DateRangePicker';
export { DatePicker } from './DatePicker';
export { TimePicker } from './TimePicker';
export { DateTimePicker } from './DateTimePicker';
export { ListPicker } from './ListPicker';
export { StatePicker } from './StatePicker';
export { StatePickerSmall } from './StatePickerSmall';

DatePicker.tsx

// Imports: Dependencies
import * as React from 'react'; 
import { DatePickerAndroid, DatePickerIOS, Dimensions, Platform, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import Modal from 'react-native-modal';
import moment from 'moment';
import Icon from 'react-native-vector-icons/Ionicons';
Icon.loadFont();

// Screen Dimensions
const { height, width } = Dimensions.get('window');

// TypeScript: Types
interface Props {
  title: string,
  onPress: Function,
  onValueChange: Function,
  mode: 'calendar' | 'spinner' | 'default',
  minDate?: Date | number;
  maxDate?: Date | number;
}

interface AndroidProps {
  action: 'dateSetAction' | 'dismissedAction',
  newDate?: Date;
  year?: number;
  month?: number;
  day?: number;
}

// Component: Date Picker
export const DatePicker = (props: Props) => {
  // React Hooks: State
  const [ modalVisible, toggle ] = React.useState(false);
  const [ date, setDate ] = React.useState(new Date());

  // Toggle Modal
  const toggleModal = async (props: Props) => {
    try {
      // Check Platform (iOS)
      if (Platform.OS === 'ios') {
        // React Hook: Toggle Modal
        toggle((modalVisible) => !modalVisible);
      }

      // Check Platform (Android)
      if (Platform.OS === 'android') {
        const { action, year, month, day } : AndroidProps = await DatePickerAndroid.open({
          date: date,
          mode: props.mode,
        });

        // Action: Date Set
        if (
          action === DatePickerAndroid.dateSetAction
          && year !== undefined
          && month !== undefined
          && day !== undefined
        ) {
          // New Date
          let newDate:Date = new Date(year, month, day);

          // Select Date
          selectDate(newDate);
        }

        // Action: Dismissed
        else if (action === DatePickerAndroid.dismissedAction) {
          // Do Nothing
        }
      };
    }
    catch (error) {
      console.log(error);
    }
  };

  // Select Date
  const selectDate = (date: Date) => {
    try {
      // React Hook: Set Date
      setDate(date);

      // React Props: onValueChange
      props.onValueChange(date);
    }
    catch (error) {
      console.log(error);
    }
  };

  // Render Picker
  const renderPicker = () => {
    try {
      return (
        <DatePickerIOS 
          mode="date"
          date={date}
          onDateChange={() => selectDate(date)}
        />
      )
    }
    catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.inputTitleContainer}>
      <Text style={styles.inputTitle}>{props.title}</Text>
      </View>

      <TouchableOpacity onPress={() => toggleModal(props)} style={styles.fieldTextContainer}>
        <Text style={styles.fieldText} numberOfLines={1}>{date ? moment(date).format('MMM Do, YYYY') : 'Select'}</Text>

        <Icon name="ios-arrow-forward" size={22} style={styles.arrowForward}/>
      </TouchableOpacity>

      <Modal isVisible={modalVisible} style={styles.modal}>
        <View style={styles.modalContainer}>
          <View style={styles.pickerHeaderContainer}>
            <TouchableOpacity onPress={() => toggleModal(props)} >
              <Text style={styles.doneText}>Done</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.pickerContainer}>
            {renderPicker()}
          </View>
        </View>
      </Modal>
    </View>
  );
}

// Styles
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    width: width - 32,
    marginLeft: 16,
    marginRight: 16,
    justifyContent: 'center',
  },
  modal: {
    margin: 0,
  },
  modalContainer: {
    height: '100%',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
  pickerHeaderContainer: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    height: 40,
    width: width,
    backgroundColor: '#FAFAF8',
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  pickerContainer: {
    height: 220,
    width: width,
    // backgroundColor: '#CFD3D9',
    backgroundColor: 'white',
  },
  doneText: {
    fontFamily: 'System',
    color: '#007AFF',
    fontWeight: '600',
    fontSize: 17,
    marginRight: 16,
  },
  stateContainer: {
    alignItems: 'center',
    width: 75,
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  inputTitleContainer: {
    width: 75,
    marginBottom: 4,
  },
  inputTitle: {
    color: '#7D7D7D',
    borderColor: '#7D7D7D',
    fontSize: 10,
    fontWeight: '600',
    textTransform: 'uppercase',
  },
  fieldTextContainer: {
    height: 40,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,    
  },
  fieldText: {
    width: width - 32 - 20,
    fontFamily: 'System',
    fontSize: 17,
    fontWeight: '400',
    color: '#000000',
    alignSelf: 'center',
  },
  arrowForward: {
    color: 'black',
    opacity: .3,
    marginRight: 7,
  },
});

package.json (Link)

My NPM package is a React Native library. I have React and React Native installed as dev dependencies as well as react and react native as peerDependencies

"name": "react-native-ultimate-modal-picker",
  "version": "0.1.6",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
    "dependencies": {
    "moment": "^2.24.0",
    "react-native-modal": "^11.5.3",
    "react-native-vector-icons": "^6.6.0"
  },
  "devDependencies": {
    "@babel/core": "7.7.7",
    "@babel/runtime": "7.7.7",
    "@react-native-community/eslint-config": "0.0.5",
    "@types/jest": "^24.0.24",
    "@types/react": "^16.9.17",
    "@types/react-native": "^0.60.25",
    "@types/react-native-vector-icons": "^6.4.5",
    "@types/react-test-renderer": "16.9.1",
    "@typescript-eslint/eslint-plugin": "^2.12.0",
    "@typescript-eslint/parser": "^2.12.0",
    "babel-jest": "24.9.0",
    "eslint": "6.8.0",
    "jest": "24.9.0",
    "metro-react-native-babel-preset": "0.56.3",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-test-renderer": "16.9.0",
    "typescript": "^3.7.3"
  },
  "peerDependencies": {
    "react": "*",
    "react-native": "*"
  },

When I use npm i react-native-ultimate-modal-picker to install the package in my project, it builds the app. However, when I finally get to the screen with the imported component, this error pops up.

enter image description here


React Navigation Typescript Error On Stack Navigator

$
0
0

I'm having a typescript issue with creating a stack navigator using React Navigation in combination with a component wrapped with a couple Higher Order Components (HOCs). I'm using compose to string my HOCs together but typescript is saying the returned component is not compatible with stack nagivator screen prop. Here is my code:

import { createStackNavigator, StackNavigationProp } from '@react-navigation/stack';
import { View, Button } from 'react-native';
import { compose } from 'recompose';
import { RouteProp } from '@react-navigation/native';

type RootStackParamList = {
  Home: IProps
};

type IProps = {
  message: string;
  user: string;
  navigation: StackNavigationProp<RootStackParamList, 'Home'>;
  route: RouteProp<RootStackParamList, 'Home'>
}

const Home = (props: IProps) => {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => alert(props.message)} title='Message' />
    </View>
  );
}
const withMessage = (Component: React.ComponentType<{ message: string }>) => <Component message='hello' />
const withUser = (Component: React.ComponentType<{ user: string }>) => <Component user='Joe' />

const homeWithMoreProps = compose<IProps, {}>(
  withMessage,
  withUser
)(Home);

const RootStack = createStackNavigator<RootStackParamList>();

<RootStack.Navigator initialRouteName='Home'>
  <RootStack.Screen name='Home' component={homeWithMoreProps} /> // <-- Error is here
</RootStack.Navigator>

Using "@react-navigation/stack": "^5.0.0-alpha.58"

The error is:

Type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' is missing the following properties from type 'Readonly<{ route: RouteProp<RootStackParamList, "Home">; navigation: any; }>': route, navigation

Basically telling me the homeWithMoreProps component is missing the navigation and route props, but based on my IProps typing it shouldn't be. I'm trying to follow these instructions but to no avail: https://reactnavigation.org/docs/en/next/typescript.html.

How to use react-native-webview-leaflet?

$
0
0

I'm devolopping an app using React Native and Expo. And I want to integrate react-native-webview-leaflet. But when I want to use the tag WebViewLeaflet so that I can be able to use WMS with GeoServer, it underlines the tag then shows this error when I hover the cursor.

JSX element type 'WebViewLeaflet' does not have any construct or call signatures.ts(2604)

Peek Problem No quick fixes available.

And when I try to run I get this errors

Some times this one

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in The fact, I have followed the step of installation but nothing work fine for me.

and other time this one

WebView has been removed from React Native. It can now be installed and imported from 'react-native-webview' instead of 'react-native'. See https://github.com/react-native-community/react-native-webview

Here is my code

import React, {Component} from 'react';
import WebViewLeaflet from 'react-native-webview-leaflet';
import { View } from 'react-native';

 export default class Map extends Component{
    render(){
      return (
        <View>
            <WebViewLeaflet/>
        </View>
      )
    }
}

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": {
    "@react-native-community/masked-view": "^0.1.6",
    "expo": "~36.0.0",
    "expo-asset": "^8.0.0",
    "expo-file-system": "^8.0.0",
    "expo-font": "^8.0.0",
    "leaflet": "^1.3.4",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz",
    "react-native-dynamic-vector-icons": "^0.2.1",
    "react-native-gesture-handler": "^1.5.3",
    "react-native-maps": "^0.26.1",
    "react-native-paper": "^2.2.2",
    "react-native-reanimated": "^1.5.0",
    "react-native-safe-area-context": "^0.6.2",
    "react-native-screens": "^2.0.0-alpha.12",
    "react-native-vector-icons": "^6.6.0",
    "react-native-web": "~0.11.7",
    "react-native-webview-leaflet": "^4.3.4",
    "react-navigation": "^4.0.10",
    "react-navigation-drawer": "^2.3.3",
    "react-navigation-material-bottom-tabs": "^2.1.5",
    "react-navigation-stack": "^2.0.15",
    "react-navigation-tabs": "^2.7.0"
  },
  "devDependencies": {
    "@types/react": "~16.9.0",
    "@types/react-native": "~0.60.23",
    "@babel/core": "^7.0.0",
    "babel-preset-expo": "~8.0.0",
    "typescript": "~3.6.3"
  },
  "private": true
}

How to specify (optional) default props with TypeScript for stateless, functional React components?

$
0
0

I'm trying to create a stateless React component with optional props and defaultProps in Typescript (for a React Native project). This is trivial with vanilla JS, but I'm stumped as to how to achieve it in TypeScript.

With the following code:

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

interface TestProps {
    title?: string,
    name?: string
}

const defaultProps: TestProps = {
    title: 'Mr',
    name: 'McGee'
}

const Test = (props = defaultProps) => (
    <Text>
        {props.title} {props.name}
    </Text>
);

export default Test;

Calling <Test title="Sir" name="Lancelot" /> renders "Sir Lancelot" as expected, but <Test /> results in nothing, when it should output "Mr McGee".

Any help is greatly appreciated.

How Would I Types to this function call?

$
0
0

The following tests pass with just import Icon from 'react-native-vector-icons/Ionicons';, but when I add Icon.loadFont(); to load the font, the following error appears. How would I add types to that function call or is that unrelated.

Code:

import Icon from 'react-native-vector-icons/Ionicons';
Icon.loadFont(); // Error here

Error (From npm test):

    RNVectorIconsManager not available, did you add 
the library to your project and link with libRNVecto
rIcons.a? Try running `react-native link react-nativ
e-vector-icons` and recompiling.
       6 | import moment from 'moment';
       7 | import Icon from 'react-native-vector-icons/Ionicons';    >  8 | Icon.loadFont();
         |      ^       9 | 
      10 | // Screen Dimensions
      11 | const { height, width } = Dimensions.get(
'window');

      at ensureNativeModuleAvailable (node_modules/r
eact-native-vector-icons/lib/ensure-native-module-av
ailable.js:13:11)
      at Function.loadFont (node_modules/react-nativ
e-vector-icons/lib/create-icon-set.js:148:7)
      at Object.<anonymous> (src/TimePicker.tsx:8:6)      at Object.<anonymous> (src/index.js:4:1)

I've already tried the recommended npm command in the error:

react-native link react-native-vector-icons

Adding non-nullable static type to memoized components throws lint error, see example for clarity

$
0
0

Example 1.

Non-nullable someStaticProperty, this will throw a lint error

import { NamedExoticComponent, memo } from "react";

type WithComponentId = { componentId: string };

type ScreenComponentStaticMembers = {
  someStaticProperty: string;
};

type AliasedType<P = {}> = NamedExoticComponent<P & WithComponentId> &
  ScreenComponentStaticMembers;

type MyComponentProps = {
  greeting: string;
};

const MyComponent: AliasedType<MyComponentProps> = memo(({ greeting }) => (
  <span>{greeting} there!</span>
));

MyComponent.someStaticProperty = "baz";

Example 2.

Optional someStaticProperty, this will work.

import { NamedExoticComponent, memo } from "react";

type WithComponentId = { componentId: string };

type ScreenComponentStaticMembers = {
  someStaticProperty?: string;
};

type AliasedType<P = {}> = NamedExoticComponent<P & WithComponentId> &
  ScreenComponentStaticMembers;

type MyComponentProps = {
  greeting: string;
};

const MyComponent: AliasedType<MyComponentProps> = memo(({ greeting }) => (
  <span>{greeting} there!</span>
));

MyComponent.someStaticProperty = "baz";
Viewing all 6206 articles
Browse latest View live