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

Property 'getPickerData' does not exist on type 'RefObject>'

$
0
0

I am trying to implement this https://github.com/thegamenicorus/react-native-phone-input/blob/master/examples/CustomPicker/app.js with typescript but it has proven rather difficult. I also just started out with react native so I don't know if I made my ref correctly but this is what I currently have.

import * as React from 'react';
import { StyleSheet, Text, View, } from 'react-native';
import {Button} from 'react-native-elements';

import PhoneInput from 'react-native-phone-input';
import ReactNativePhoneInput from 'react-native-phone-input';
// import CountryPicker from 'react-native-country-picker-modal';

export interface IRegisterScreenProps {

}

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : string;
}

export default class RegisterScreen extends React.Component<IRegisterScreenProps, IRegisterScreenState> {

  private phoneInputRef = React.createRef<ReactNativePhoneInput>();

  constructor(props:IRegisterScreenProps) {
    super(props);
    this.onPressFlag = this.onPressFlag.bind(this);
    this.selectCountry = this.selectCountry.bind(this);
    this.submitPhoneNumber = this.submitPhoneNumber.bind(this);
    this.state = {
      cca2: 'US',
    };
  }

  componentDidMount() { 
    if (this.phoneInputRef) 
      this.setState({pickerData: this.phoneInputRef.getPickerData()}); 
  }

  onPressFlag() {
    // this.countryPicker.openModal();
    console.log(this.phoneInputRef);
  }

  selectCountry(country:IRegisterScreenState) {
    if(this.phoneInputRef)
      this.phoneInputRef.selectCountry(country.cca2.toLowerCase());
    // this.setState({ cca2: country.cca2 });
  }

  public render(): JSX.Element
  {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tempp</Text>
        <PhoneInput ref={this.phoneInputRef} onPressFlag={this.onPressFlag}/>
        <Button title="Submit" onPress={this.submitPhoneNumber} containerStyle={styles.submitButton} />
      </View>
    );
  }

  private submitPhoneNumber() : void
  {
    console.log(this.phoneInputRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 50,
    margin: 30,
  },
  phoneNumberInput:{
    width: 300,
  },
  submitButton:{
    width: 150,
    margin: 25,
  },
});

But it throws an error on this.phoneInputRef.selectCountry(country.cca2.toLowerCase()); and this.setState({pickerData: this.phoneInputRef.getPickerData()}); saying

Property 'selectCountry' does not exist on type 'RefObject<ReactNativePhoneInput<typeof TextInput>>'

I installed the types for react-native-phone-input and I navigated to the object and saw that it did implement it. How is this possible? I added the file I navigated to.

// Type definitions for react-native-phone-input 0.2
// Project: https://github.com/thegamenicorus/react-native-phone-input
// Definitions by: Matthew Elphick <https://github.com/maael>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.9

import * as React from 'react';
import { StyleProp, ViewStyle as ViewStyleRaw, TextStyle as TextStyleRaw, TextInput, ImageRequireSource } from 'react-native';

export type ViewStyle = StyleProp<ViewStyleRaw>;
export type TextStyle = StyleProp<TextStyleRaw>;

export interface CountriesListItem {
  name: string;
  iso2: string;
  dialCode: string;
  priority: number;
  areaCodes: ReadonlyArray<string> | null;
}

export interface PickerData {
  key: number;
  image: ImageRequireSource;
  label: CountriesListItem['name'];
  dialCode: CountriesListItem['dialCode'];
  iso2: CountriesListItem['iso2'];
}

export interface ReactNativePhoneInputProps<TextComponentType extends React.ComponentType = typeof TextInput> {
    /**
     * Initial selected country
     */
    initialCountry?: string;
    /**
     * Allow user input 0 after country code
     */
    allowZeroAfterCountryCode?: boolean;
    /**
     * If true, disable all interaction of this component
     */
    disabled?: boolean;
    /**
     * Initial phone number
     */
    value?: string;
    /**
     * Custom styles to be applied if supplied
     */
    style?: ViewStyle;
    /**
     * Custom styles for flag image eg. {{width: 50, height: 30, borderWidth:0}}
     */
    flagStyle?: ViewStyle;
    /**
     * Custom styles for phone number text input eg. {{fontSize: 14}}
     */
    textStyle?: TextStyle;
    /**
     * Properties for phone number text input eg. {{placeholder: 'Telephone number'}}
     */
    textProps?: React.ComponentProps<TextComponentType>;
    /**
     * The input component to use
     */
    textComponent?: TextComponentType;
    /**
     * Distance between flag and phone number
     */
    offset?: number;
    /**
     * Set button color of country picker
     */
    pickerButtonColor?: string;
    /**
     * Set background color of country picker
     */
    pickerBackgroundColor?: string;
    /**
     * Custom styles for text in country picker eg. {{fontSize: 14}}
     */
    pickerItemStyle?: ViewStyle;
    /**
     * Cancel word
     */
    cancelText?: string;
    /**
     * Confirm word
     */
    confirmText?: string;
    /**
     * Custom styles for country picker button
     */
    buttonTextStyle?: TextStyle;
    /**
     * Function to be invoked when phone number is changed
     */
    onChangePhoneNumber?: (number: number) => void;
    /**
     * Function to be invoked when country picker is selected
     */
    onSelectCountry?: (iso2: string) => void;
    /**
     * Function to be invoked when press on flag image
     */
    onPressFlag?: () => void;
    /**
     * Custom countries list
     */
    countriesList?: ReadonlyArray<CountriesListItem>;
    /**
     * Function to be invoked when cancelling country picker selection
     */
    onPressCancel?: () => void;
    /**
     * Function to be invoked when confirming country picker selection
     */
    onPressConfirm?: () => void;
}

export default class ReactNativePhoneInput<
                   TextComponentType extends React.ComponentType = typeof TextInput
               > extends React.Component<ReactNativePhoneInputProps<TextComponentType>> {
                   picker?: React.Ref<ThisType<ReactNativePhoneInput>>;
                   /**
                    * Return true if current phone number is valid
                    */
                   isValidNumber: () => boolean;
                   /**
                    * Return true type of current phone number
                    */
                   getNumberType: () => string;
                   /**
                    * Return current phone number
                    */
                   getValue: () => string;
                   /**
                    * Return flag image
                    */
                   getFlag: (iso2: string) => ImageRequireSource;
                   /**
                    * Return country object in country picker
                    */
                   getAllCountries: () => CountriesListItem;
                   /**
                    * Return country object with flag image
                    */
                   getPickerData: () => PickerData;
                   /**
                    * Focus the phone input
                    */
                   focus: () => void;
                   /**
                    * Blur the phone input
                    */
                   blur: () => void;
                   /**
                    * Set phone input to specific country
                    */
                   selectCountry: (iso2: string) => void;
                   /**
                    * Return country dial code of current phone number
                    */
                   getCountryCode: () => string;
                   /**
                    * Return country iso code of current phone number
                    */
                   getISOCode: () => string;
               }

How can I set a state with react native and typescript?

$
0
0

I'm just started with react native and I'm trying to use typescript. I am trying to set my state but it gives me the following error.

Argument of type '{ pickerData: PickerData; }' is not assignable to parameter of type 'IRegisterScreenState | ((prevState: Readonly<IRegisterScreenState>, props: Readonly<IRegisterScreenProps>) => IRegisterScreenState | Pick<...>) | Pick<...>'.
  Type '{ pickerData: PickerData; }' is not assignable to type 'Pick<IRegisterScreenState, "pickerData">'.
    Types of property 'pickerData' are incompatible.
      Type 'PickerData' is missing the following properties from type 'ReactNativePhoneInput<typeof TextInput>': isValidNumber, getNumberType, getValue, getFlag, and 14 more.

I looked up on how to set a state using typescript an I found the following https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native#adding-a-component where they use the interface State and Props. Can I not make my own interface for this component? I've seen others do IState and IProps. Otherwise I woul not know what is causing my error. The error comes from the following line this.setState({pickerData: this.phoneInputRef.current.getPickerData()});

import * as React from 'react';
import { StyleSheet, Text, View, } from 'react-native';
import {Button} from 'react-native-elements';

import PhoneInput from 'react-native-phone-input';
import ReactNativePhoneInput from 'react-native-phone-input';
import PickerData from 'react-native-phone-input';
// import CountryPicker from 'react-native-country-picker-modal';

export interface IRegisterScreenProps {

}

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : PickerData;
}

export default class RegisterScreen extends React.Component<IRegisterScreenProps, IRegisterScreenState> {

  private phoneInputRef = React.createRef<ReactNativePhoneInput>();

  constructor(props:IRegisterScreenProps) {
    super(props);
    this.onPressFlag = this.onPressFlag.bind(this);
    this.selectCountry = this.selectCountry.bind(this);
    this.submitPhoneNumber = this.submitPhoneNumber.bind(this);
    this.state = {
      cca2: 'US',
    };
  }

  componentDidMount() { 
    if (this.phoneInputRef.current) 
      this.setState({pickerData: this.phoneInputRef.current.getPickerData()}); 
  }

  onPressFlag() {
    // this.countryPicker.openModal();
    console.log(this.phoneInputRef.current);
  }

  selectCountry(country:IRegisterScreenState) {
    if(this.phoneInputRef.current)
      this.phoneInputRef.current.selectCountry(country.cca2.toLowerCase());
    // this.setState({ cca2: country.cca2 });
  }

  public render(): JSX.Element
  {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tempp</Text>
        <PhoneInput ref={this.phoneInputRef} onPressFlag={this.onPressFlag}/>
        <Button title="Submit" onPress={this.submitPhoneNumber} containerStyle={styles.submitButton} />
      </View>
    );
  }

  private submitPhoneNumber() : void
  {
    console.log(this.phoneInputRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 50,
    margin: 30,
  },
  phoneNumberInput:{
    width: 300,
  },
  submitButton:{
    width: 150,
    margin: 25,
  },
});

createBottomTabNavigator in react native have a small clickable zone

$
0
0

My problem is with a bottom bar navigation that I created for a react native app. All the tabs work fine and navigate correctly, but when i click in another tab ( the third one for example), the clickable zone for the previous tabs is reduced. I need to click a small area in the corner of the tab .

My code for bottom bar :

const tabNav = createBottomTabNavigator({
  test: {
    screen: test,
    navigationOptions: {
      tabBarLabel: "Home",
      tabBarIcon: ({ tintColor, navigation }) => (
        <Ionicons name="ios-home" color={tintColor} size={25} />
      )
    }
  },

  FlashNews: {
    screen: FlashNews,
    navigationOptions: {
      tabBarLabel: "Flash News",
      tabBarIcon: ({ tintColor }) => (
        <Entypo name="flash" color="#000000" size={25} />
      )
    }
  },
  favoris: {
    screen: favoris,
    navigationOptions: {
      tabBarLabel: "Favoris",
      tabBarIcon: ({ tintColor }) => (
        <FontAwesome5 name="heart" size={25} color="#6f6f6f" />
      )
    }
  },

  CodePromo: {
    screen: CodePromo,
    navigationOptions: {
      tabBarLabel: "Code Promo",
      tabBarIcon: ({ tintColor }) => (
        <MaterialCommunityIcons name="barcode" size={25} />
      )
    }
  }
});

the bottomNvigator work togther with drawer navigator , my code is :

const DrawerStackECommerce = createDrawerNavigator(
  {
    tabNav: { screen: tabNav },
    //ECommerceMenu: { screen: ECommerceMenu },
    ECommerceAddress: { screen: ECommerceAddress },
    PrixNeuf: {
      screen: PrixNeuf
    },

    AnnonceChild: {
      screen: AnnonceChild,
      navigationOptions: ({ navigation }) => ({
        header: null,
        tabBarVisible: false,
        headerMode: "screen"
      })
    },
    BlogChild: {
      screen: BlogChild,
      navigationOptions: ({ navigation }) => ({
        header: null,
        tabBarVisible: false,
        headerMode: "screen"
      })
    },

    webV: {
      screen: webV,
      navigationOptions: ({ navigation }) => ({
        header: null,
        tabBarVisible: false,
        headerMode: "screen"
      })
    },
    BlogChild: {
      screen: BlogChild,
      navigationOptions: ({ navigation }) => ({
        header: null,
        tabBarVisible: false,
        headerMode: "screen"
      })
    },

    ECommerceChangePassword: { screen: ECommerceChangePassword },

    //PrixNeuf : {screen : PrixNeuf},
    MonCompte: { screen: MonCompte },
    ECommerceMyInformation: { screen: ECommerceMyInformation },
    ECommerceNotification: { screen: ECommerceNotification },
    email: { screen: email },
    Search: { screen: Search },
    SearchPrix: { screen: SearchPrix },
    ECommerceLogin: { screen: ECommerceLogin },
    ECommerceForgotPassword: { screen: ECommerceForgotPassword },
    ECommerceResetPassword: { screen: ECommerceResetPassword },
    ECommerceEditInformation: { screen: ECommerceEditInformation },

    //AnnonceDetails: { screen: AnnonceDetails },
    AddAnnonce: { screen: AddAnnonce },
    //BlogDetails: { screen: BlogDetails },
    //Annonces: { screen: Annonces },
    maps: { screen: maps },
    pdf: { screen: pdf }
  },
  {
    gesturesEnabled: false,
    contentComponent: WooCommerceSideMenu
  }
);

So when i am in the third section in bottom navigator for example, like in this image, to return to home I need to click to the top left of icon home in a small area.

Please can you help me to solve my problem to make all the area zone of home icon clickable , and to understand why i face this problem .

enter image description here

thank you for your help.

TypeError: _getPrototypeOf2 is undefined

$
0
0

I use react-native-web with typescript and when I'm trying to run my project I get this error

TypeError: _getPrototypeOf2 is undefined in react-navigation-stack/lib/module/vendor/views/Stack/StackView.js:1

here my my babel config

test: /\.js$/,
  // Add every directory that needs to be compiled by Babel during the build.

  use: {
    loader: "babel-loader",
    options: {
      //cacheDirectory: true,

      presets: ["module:metro-react-native-babel-preset"],

      plugins: [
        "react-native-web",
        "transform-react-remove-prop-types",
        ["@babel/plugin-proposal-decorators", { legacy: true }],
        [
          "@babel/plugin-transform-runtime",
          {
            helpers: true,
            regenerator: false
          }
        ]
      ]
    }
  }

TypeScript complains about conditionally assigning class: JSX element type 'TouchableComponent' does not have any construct or call signatures

$
0
0

I have this piece of code:

protected getCardContent = (message: string): JSX.Element => {
    const { placeInfo } = this.props;
    const TouchableComponent = Platform.OS === 'ios' ? TouchableOpacity : TouchableNativeFeedback
    return (
        <View>
            <Text>{placeInfo.name}'s phone number:</Text>
            <TouchableComponent onPress={() => {}}>
                <Text>{placeInfo.phoneNumber}</Text>
            </TouchableComponent>
        </View>
    )
}

When calling this.getCardContent in my render method it works on both iOS and Android devices; however, TS complains saying:

const TouchableComponent: typeof TouchableOpacity | typeof TouchableNativeFeedback
JSX element type 'TouchableComponent' does not have any construct or call signatures.

Is it because TouchableComponent can be of either constructor type, thus TS doesn't explicitly know what the instantiated type is? What would be a better way to solve this issue that works with the TS compiler?

react-native run-android getting error : A problem occurred evaluating project ':app'.([androidx.appcompat:appcompat:1.1.0-rc01])

$
0
0

I have created a new project by using react-native init but I'm getting the following error

FAILURE: Build failed with an exception.
* Where:
Build file '/Users/vahiddavoudi/Project/BBW/android/app/build.gradle' line: 202

* What went wrong:
A problem occurred evaluating project ':app'.
 **Could not find method implementation() for arguments [androidx.appcompat:appcompat:1.1.0-rc01] on project ':app' of type org.gradle.api.Project.**

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#andr
oid-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

Versions:

  • react: 16.9.0
  • react-native: 0.61.1

Note: environment variables in bash_profile are setup. I have also tried to remove node_module and run yarn but no success

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.

Where are the compiled typescript js files for my react-native expo application?

$
0
0

I just created one of the default typescript expo projects with expo init, and it has a simple App.tsx file in the main directory. I'm able to make changes to the file and have those changes reflected in my app, but I can't seem to find the corresponding output file:App.js file anywhere, which I find very confusing.

After digging in the provided tsconfig.json, it has an option clearly labeled "noEmit": true, which turns off any output files during the compilation, which doesn't make a whole lot of sense to me.

Where are the typescript output files being saved / watched?


How to target and set styles between styled components in React Native withTypescript

$
0
0

I want to do like I always did in React with Styled Components.

import styled from "styled-components";

import {Wrapper as CardComponent} from '../../components/Card/style';

export const Wrapper = styled.div`
 ${CardComponent}{
 ...the styles
}
`

But this isn't working with React Native.

import styled from "styled-components/native";

import {Wrapper as CardComponent} from '../../components/Card/style';

export const Wrapper = styled.View`
 ${CardComponent}{
 ...the styles
}
`

There is any way to target and set rules between styled components in react native?

withNavigationFocus throwing lint error - React Native Typescript

$
0
0

I'm trying to use withNavigationFocus for a component as code been written in Typescript. ,

my component props

   interface IScreenProps {
  navigation: NavigationScreenProp<NavigationState, IParamsNavigate>;
  departments: NavigationNode[] | null;
  updateSearchCriteria: (searchCriteria: ISearchCriteria, stack: StackNames) => void;
  resetProductState: () => void;
  isFocused: boolean;
}

component

class SearchScreen extends React.Component<IScreenProps, IScreenState> {

.....

}

export default connect(mapStateToProps, mapDispatchToProps)( withNavigationFocus(SearchScreen));

there is no build error , still in red line is showing in editor/IDE on searchScreen export. .I have enclosed error i'm facing below.

enter image description here

Please let me know how i can fix this.

Is it already possible to use top-level await in react-native?

$
0
0

Is it already possible to use top-level await in react-native? I saw it's been added to TypeScript 3.8 (I was not using TS, I just tried to see if it would help but no). However in react-native file transform is handled by babel and I don't think the current metro preset handles top-level awaits. Is there any way to make it work?

React-native: Exporting a user defined type as default causes "can't find variable" error

$
0
0

I'm using React and React-native for my web application and mobile projects. both projects are written in typescript.

In the React web application, I have defined a type C and exported it as default;

myTypes.ts

export interface A {
    // a few attributes
}

export interface B {
    // a few attributes
}

type C = A | B;

export default C;

so I can simply import C using import C from 'PATH/TO/myTypes';

I using the same file in my React-Native project but when I run the application I got can't find variable: C error message.

The error is gone when I made these changes

+export type C = A | B; // export C at this line

-export default C; // and removing this line

and import C using import { C } from 'PATH/TO/myTypes';

I'm wondering why I can't export a user-defined type as default in React-Native.

It worths to mention that I'm using the same typescript version for both projects. other information about typescript related dependencies is listed below.

React-Native project:

  1. "tslint": "5.17.0"
  2. "tslint-react": "4.0.0"
  3. "type-zoo": "3.4.1"
  4. "typescript": "3.7.5"
  5. "@babel/core": "7.4.5"
  6. "@babel/runtime": "7.4.5"

React project:

  1. "type-zoo": "3.4.1",
  2. "typescript": "3.7.5"

Setup for React Native/TypeScript/Testing Library/Jest not working

$
0
0

I'm trying to setup a React Native/TypeScript application to be tested with Jest and @testing-library/react-native;

So far I'm getting this error:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Previously I faced a Missing class properties transform error, so I added @babel/plugin-proposal-class-properties to the Babel config already included in the original bootstrapping with expo init, but once I do that I get this other error, and nothing I've tried so far works.

This is my babel config:

module.exports = function(api) {
  api.cache(true);
  return {
    presets: [
      "babel-preset-expo",
      ["@babel/preset-env", { targets: { node: "current" } }],
      "@babel/preset-typescript"
    ],
    plugins: ["@babel/plugin-proposal-class-properties"]
  };
};

and my Jest configuration:

"jest": {
   "preset": "react-native"
}

The breaking test:

import React from "react";
import App from "../App";
import { render } from "@testing-library/react-native";

describe("App", () => {
  it("renders", () => {
    const { container: received } = render(<App />);

    expect(received).toMatchSnapshot();
  });
});

Please note that I've spent some time trying different combinations of presets/plugins/configs so this may not be the ideal setup. I'm trying to understand if there is an actual limitation of this specific stack that I've chosen (so far I couldn't find a precise up to date example using this exact stack), a misconfiguration, or an actual bug that I should raise. I also don't know to which package the bug --if any-- actually belongs, should I report it to Jest? Or React Native? or Babel? Or Testing Library?

Any help would be greatly appreciated.

Thanks!

Type issue in Typescript React-native styled-component

$
0
0

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

here is my code

interface IDefaultStyle {
  style?: object
}

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

And the type error is

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

Type Error

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

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

My package.json

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

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

Edit component usage

/**
 * ## AuthorView  | SellerView
 * Component to show Author info
 * @param props
 */
const AuthorView = (props: IProps) => {

  const { name, style, imageUrl, rating, subtext, onPress } = props

  // if imageUrl is not provided use default star icon
  const imageSource = imageUrl ? { uri: imageUrl } : require('../../icons/star-grey.png')

  return(
    <RootContainer onPress={onPress} style={style}>
        <ImageViewContainer>
            <ImageView
              defaultImage={imageUrl ? false : true}
              source={ imageSource }
            />
        </ImageViewContainer>
        <RightContainer>
            <Name>{name}</Name>
            <View style={{ flexDirection: 'row' }}>
            {rating && <RatingView style={{ marginRight: 3 }} rating={rating} />}
            <SubText>{subtext}</SubText>
            </View>
        </RightContainer>
    </RootContainer>
  )
}

export default AuthorView

Conditional Rendering with Mutations

$
0
0

I am using a graphQL mutation in the function SubmitForm(), which returns a token and saves it in local storage if the username/password are correct. If not, .catch() catches an error. I want that if the login is not successful, I should be able to display a snack bar/typography etc. How can I do so in this case?

function LoginPage (){
  const [state, setState] = useState({
    email: '',
    password: '',
    loggedIn: false,
  });  


  function submitForm(LoginMutation: any) {
    const { email, password } = state;
    console.log(email, password)
    if(email && password){
      LoginMutation({
        variables: {
            email: email,
            password: password,
        },
    }).then(({ data }: any) => {
      localStorage.setItem('token', data.loginEmail);
    })
    .catch(console.log)
    }
  }

    return (
      <Mutation mutation={LoginMutation}>
        {(LoginMutation: any) => (
          <Container component="main" maxWidth="xs">
            <CssBaseline />
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center'
            }}>
              <Avatar>
                <LockOutlinedIcon />
              </Avatar>
              <Typography component="h1" variant="h5">
                Sign in
              </Typography>
              <Formik
                initialValues={{ email: '', password: '' }}
                onSubmit={(values, actions) => {
                  setTimeout(() => {
                    alert(JSON.stringify(values, null, 2));
                    actions.setSubmitting(false);
                  }, 1000);
                }}
                validationSchema={schema}
              >
                {props => {
                  const {
                    values: { email, password },
                    errors,
                    touched,
                    handleChange,
                    isValid,
                    setFieldTouched
                  } = props;
                  const change = (name: string, e: any) => {
                    e.persist();                
                    handleChange(e);
                    setFieldTouched(name, true, false);
                    setState( prevState  => ({ ...prevState,   [name]: e.target.value }));  
                  };
                  return (
                    <form style={{ width: '100%' }} onSubmit={e => {e.preventDefault();submitForm(LoginMutation)}}>
                      <TextField
                        variant="outlined"
                        margin="normal"
                        id="email"
                        fullWidth
                        name="email"
                        helperText={touched.email ? errors.email : ""}
                        error={touched.email && Boolean(errors.email)}
                        label="Email"     
                        value={email}
                        onChange={change.bind(null, "email")}
                      />
                      <TextField
                        variant="outlined"
                        margin="normal"
                        fullWidth
                        id="password"
                        name="password"
                        helperText={touched.password ? errors.password : ""}
                        error={touched.password && Boolean(errors.password)}
                        label="Password"
                        type="password"
                        value={password}
                        onChange={change.bind(null, "password")}
                      />
                      <FormControlLabel
                        control={<Checkbox value="remember" color="primary" />}
                        label="Remember me"
                      />
                      <br />
                      <Button className='button-center'
                        type="submit"
                        disabled={!isValid || !email || !password}
                        style={{
                          background: '#6c74cc',
                          borderRadius: 3,
                          border: 0,
                          color: 'white',
                          height: 48,
                          padding: '0 30px'
                        }}
                      >
                        Submit</Button>
                      <br></br>
                      <Grid container>
                        <Grid item xs>
                          <Link href="#" variant="body2">
                            Forgot password?
                    </Link>
                        </Grid>
                        <Grid item>
                          <Link href="#" variant="body2">
                            {"Don't have an account? Sign Up"}
                          </Link>
                        </Grid>
                      </Grid>
                    </form>
                  )
                }}
              </Formik>
            </div>
            <Box mt={8}>
              <Copyright />
            </Box>
          </Container>
          )
        }
      </Mutation>
    );
}

export default LoginPage;

I tried writing this after the .catch() but I get an error that name data isn't found. But either way I don't feel that this is the correct way to do so.

   if (!data.loginEmail)
    {
      return <Typography> Invalid </Typography>
    }

Performance optimization for react-native-canvas when drawing many paths

$
0
0

I want to mirror an analog segment display in my React Native app. The segment display is quite complicated, it consists of more than 100 different segments. It contains three 7-segment displays for numbers and a progress bar with 20 elements. The rest are custom shapes and symbols that provide information about the current state of the machine it is attached to. I have some experience with the HTML canvas and found the React Native module react-native-canvas and wanted to give it a try. However, drawing on the react-native-canvas seems to be quite slow compared to the HTML canvas that I can use in a web-browser.

Here is what I do:

  1. I import the module in my component:

import Canvas, {Image as CanvasImage, Path2D, ImageData} from 'react-native-canvas';

  1. Add a canvas element to my render function:

<Canvas ref={this.handleCanvas}/>

  1. store a reference to the canvas and set its size:
handleCanvas = (canvas) => {
    if (this.myCanvas === null && canvas !== null){
      canvas.width = 250;
      canvas.height = 250;
      this.myCanvas = canvas;
    }
  }
  1. Then i can call for each segment a "draw" function that draws a 2D-path:
draw(ctx){
  ctx.save();
  ctx.strokeStyle="#000000";
  ctx.lineWidth=2;
  ctx.lineJoin="round";
  ctx.font="   10px sans-serif";
  ctx.beginPath();
  ctx.moveTo(158.108112514019,24.324327290058136);
  ctx.lineTo(159.45946389436722,24.324327290058136);
  ctx.lineTo(160.13513958454132,25.67567867040634);
  ...
  ctx.lineTo(162.16216665506363,25.00000298023224);
  ctx.fill("nonzero");
  ctx.stroke();
  ctx.restore();
}

I get the context like this: var ctx = this.myCanvas.getContext('2d');

I made a prototype with 13 segments. Each segment has around 50 nodes and I draw all 13 segments at once. In my React Native app, this takes almost one second to draw which is way too slow (and there are 90 more segments that I do not render yet...). If I draw the same paths on a HTML canvas on Google Chrome, it only takes 2-5 milliseconds.

Does anyone have an idea, how I can improve the performance? Or is there another library that is more performant for my purposes?`

Thanks in advance!

How to pass data back to previous screen in react native navigation v5?

$
0
0

I just updated to react native navigation version 5. Now I am trying to send data back to previous screen on goBack() call.

I push next view with

const onSelectCountry = item => {
    console.log(item);
};

navigation.navigate('SelectionScreen', {
        onSelect: onSelectCountry});

And making move back after selecting item from FlatList with call:

function onSelectedItem(item) {
    route.params.onSelect(item);
    navigation.goBack();
}

But by sending function over with params I get a warning: Non-serializable valuse were found in the navigation state...

Can someone please tell me correct way to do this.

Typescript React handleChange() or handleSubmit() Form not working

$
0
0

I'm working on my first typescript react project so I'm a beginner trying to go through the loops. I have a form with 3 different select fields. For now what I'm trying to do is when you submit the form for it to display the values you selected.

With my code below if I were to change a select option lets say from yes to no, in my console for that handleChange it will display null for that event. Also, when I submit the form for any field in which I have changed the select value it will display undefined in the alert.

I did notice that whenever I select a value in the drop down that the console reloads. So I'm not to sure if that's what is causing it to display a null.

I'm looking for the best way to store the selection that the user selected:

import * as React from 'react';
import styles from './TeacherSelector.module.scss';
import { ITeacherSelectorProps } from './ITeacherSelectorProps';


export default class TeacherSelector extends React.Component<ITeacherSelectorProps, {tenure: string, grade: string, location: string}> {

    constructor(props) {
        super(props);
        this.state = {
            tenure: 'yes',
            grade: 'first',
            location: 'new-york',
        };

        this.handleChangeTenure = this.handleChangeTenure.bind(this);
        this.handleChangeGrade = this.handleChangeGrade.bind(this);
        this.handleChangeLocation = this.handleChangeLocation.bind(this);

        this.handleSubmit= this.handleSubmit.bind(this);            

    }

    handleChangeTenure(event) {
        console.log(event);
        this.setState({tenure: event.target.tenure});
    }

    handleChangeGrade(event) {
        console.log(event);
        this.setState({grade: event.target.grade});
    }

    handleChangeLocation(event) {
        this.setState({location: event.target.location});
    }

    handleSubmit(event) {
        event.preventDefault();
        alert('Tenure: ' + this.state.tenure + 'Grade: ' + this.state.grade + 'Location: ' + this.state.location);
    }


    public render(): React.ReactElement<ITeacherSelectorProps> {

        return (
            <div className={ styles.TeacherSelector }>
                <div className={ styles.container }>
                    <div className={ styles.row }>
                        <div className={ styles.column }>

                            <form onSubmit={this.handleSubmit}>
                                <label>
                                    Tenure (YES/NO):
                                    <select name="tenure" value={this.state.tenure} onChange={(Val: any) => this.handleChangeTenure(Val)}>
                                        <option value="yes">Yes</option>
                                        <option value="no">No</option>
                                    </select>
                                </label>

                                <label>
                                    Teaching Grade Level
                                    <select  name="grade" value={this.state.grade} onChange={this.handleChangeGrade}>
                                        <option value="first">first</option>
                                        <option value="second">second</option>
                                        <option value="third">third</option>
                                        <option value="fourth">fourth</option>                                        
                                    </select>
                                </label>

                                <label>
                                    Location
                                    <select name="location" value={this.state.location} onChange={this.handleChangeLocation}>
                                        <option value="new-york">New York</option>
                                        <option value="queens">Queens</option>
                                        <option value="new-jersey">New Jersey</option>
                                    </select>
                                </label>                                

                                <input type="submit" value="Submit" />
                            </form>                         

                        </div>
                    </div>
                </div>
            </div>
        );
      }


}

Dropdown/Select Value Not Changing - useState

$
0
0

My dropdown menu (Material UI select) says "Search By" and then we click on it, it gives a list. When I select on of the options, I want to store the option and change the "Searchh By" to the selected option.

export default function UserSearchPage(){
  const [criteria, setCriteria] = useState('');
  const [searchItem, setSearchItem] = useState('');
  return (
    <div>
      <div className='main-content'>
        <Select 
        value = {criteria}
         onChange={value => {
          setCriteria(value);}}
        displayEmpty>
          <MenuItem disabled value="">
            <em>Search By</em>
          </MenuItem>
          <MenuItem value={1}>First Name</MenuItem>
          <MenuItem value={2}>Last Name</MenuItem>
          <MenuItem value={3}>Phone Number</MenuItem>
          <MenuItem value={4}>Email</MenuItem>
        </Select>
        <br></br><br></br>
         <SearchBar
         value= {searchItem}
         onChange={value => {
          setSearchItem(value);}}
            onRequestSearch={() => console.log('onRequestSearch')}
            style={{
              margin: '0 auto',
              maxWidth: 800
            }}
          />
            </div>
          )
    </div>
  );
}

With my current onChange on the Select, I get this error on value:

Argument of type 'ChangeEvent<{ name?: string | undefined; value: unknown; }>' is not assignable to parameter of type 'SetStateAction<string>'.
  Type 'ChangeEvent<{ name?: string | undefined; value: unknown; }>' is not assignable to type '(prevState: string) => string'.

If I use this onChange:

onChange={event => setCriteria(event.target.value)}

I get an error that:

Argument of type 'unknown' is not assignable to parameter of type 'SetStateAction<string>'.
  Type 'unknown' is not assignable to type '(prevState: string) => string'.

I tried creating a sandbox but I have no idea how to resolve the error. The code looks fine but it doesn't compile: https://codesandbox.io/s/sleepy-buck-5t7bq

onCompleted for Mutation giving console error

$
0
0

If the mutation is not successful, I want to show the user a message. Fow now, I tried to print it on console but I get an error on onCompleted that:

Type 'void' is not assignable to type '((data: any) => void) | undefined'.ts(2322)

Code

  function submitForm(RemoveUserMutation: any) {
    const { email} = state;
    if(email){
      RemoveUserMutation({
        variables: {
            email: email,
        },
    }).then(({ data }: any) => {
      console.log('info: ', data.deleteUser);
    })
    .catch(console.log)
    }
  }

  return (
    <Mutation mutation={RemoveUserMutation}>
      {(RemoveUserMutation: any) => (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        initialValues={{ email: '' }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
        }}
        validationSchema={schema}
      >
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched
          } = props;
          const change = (name: string, e: any) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
            setState( prevState  => ({ ...prevState,   [name]: e.target.value }));  
          };
          return (
            <div className='main-content'>
              <form style={{ width: '100%' }}
               onSubmit={e => {e.preventDefault();
                submitForm(RemoveUserMutation)}}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ""}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, "email")}
                  />
                  <br></br>
                  <Button
                  type="submit"
                  disabled={!isValid || !email}
                    style={{
                      background: '#6c74cc',
                      borderRadius: 3,
                      border: 0,
                      color: 'white',
                      height: 48,
                      padding: '0 30px',
                    }}
                  >
                    Remove User</Button>
                </div>
              </form>
            </div>
          )
        }}
      </Formik>
    </div>
      )}
     </Mutation>
  );
}

I also tried this but doesn't really help since idk how to show the user a message that the mutation is successful or not. It could be a typography too, or alert.

onCompleted= {(e: any) => setStatus(true)}
Viewing all 6417 articles
Browse latest View live


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