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

Using activeStorage with i18n on expo not working

$
0
0

Trying to set an app using Typescript React on expo that can show a different language based on a user selection, but doesn't seem to be working.I've made it store the selected language in asyncStorage and called await AsyncStorage.getItem('language') to get the language, my code is below. If console.log is run on asyncStorage, I was able to retrieve the value.

Interestingly, language works without any flaws when I use Localization.locale, so wondering if it's being asyncStorage is taking too long to get a result?

import I18n from 'i18n-js'import AsyncStorage from '@react-native-community/async-storage'import en from './en.json'import zh from './zh.json'I18n.translations = {  en,  zh}async function getLanguage() {  try {    const value = await AsyncStorage.getItem('language')    if (value != null) {      I18n.locale = value.slice(0,2)      I18n.fallbacks = true    }  } catch(e) {    console.log(e)  }}getLanguage()export function t(name: string) {  return I18n.t(name)}

Language selector (stores the selected language in asyncStorage)

import AsyncStorage from '@react-native-community/async-storage'import { Updates } from 'expo';export default function LanguageChange() {const onPress = async (language: string) => {    await AsyncStorage.setItem('language', language);    Updates.reload();} return (<View style={styles.languageContainer}><TouchableOpacity onPress={() => onPress("en")}><Text>English</Text></TouchableOpacity><TouchableOpacity onPress={() => onPress('zh-CN')}><Text>Chinese</Text></TouchableOpacity></View>  );}

Edit 1

I've tried using .then as well to see if there was a different result, but it's still the same.

AsyncStorage.getItem('language').then((result) => {  I18n.locale = result.slice(0,2)})

typescript extension in VSCode

$
0
0

I just created a sample react-native project with the following command.

react-native init SampleProject --template typescript

Then I got the red line of Editor. How to fix this?

I guess this concerns with extension.What extension should I install for typescript in react-native?

enter image description here

This is the image that I hover mouse on tag.enter image description here

Value type for Material UI's Select component

$
0
0

I am using Material UI's Select component (which is like a drop down menu) like this:

const [criteria, setCriteria] = useState('');...  let ShowUsers = () => {    console.log('Working criteria', typeof(criteria));    const where: UserFilter = {};    if (criteria == '1') {      loadUsers({        variables: {          where: where,        },      });    }    if (criteria == '2') {      if (searchItem) {        where.firstName_contains = searchItem;        loadUsers({          variables: {           where: where,          },        });      }    }}...return(<Select          value={criteria}          onChange={event => setCriteria(event.target.value as string)}          //onChange={event => setCriteria(event.target.value)}          displayEmpty><MenuItem disabled value=""><em>Search By</em></MenuItem><MenuItem value={1}>All</MenuItem><MenuItem value={2}>First Name</MenuItem></Select><Button onClick={() => ShowUsers()}>Search</Button>)

Currently this gives me a warning that

Expected '===' and instead saw '=='  eqeqeq

To investigate this, I tried to print out the typeof(criteria) in the showUsers function. The type is number.

Hence, I changed (criteria === 1) etc. But then it gives an error that This condition will always return 'false' since the types 'string' and 'number' have no overlap.ts. But both are already numbers so I don't quite understand this.

Additionally, I also tried changing things like this:

const [criteria, setCriteria] = useState<number>();..onChange={event => setCriteria(Number(event.target.value))}

However, then I get new warnings that:

you have provided an out-of-range value `undefined` for the select component.Consider providing a value that matches one of the available options or ''.The available values are ``, `1`, `2`.
Warning: A component is changing an uncontrolled input of type hidden to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. 

and if I simply use criteria === '1' without changing anything else, the conditions are never made true even when they should be.

Where am I going wrong? Probably something minor.

useState with interface- react native typescript

$
0
0

there is a way to use useState with an interface type?

This is what i'm tryint to do :

const [movie, setMovie] = useState(null);[...].then((responseJson) => {            var movie: Movie = {                id : id,                title: responseJson.original_title,                backdrop: "https://image.tmdb.org/t/p/original" + responseJson.backdrop_path,                note: responseJson.vote_average,                numberNote: responseJson.vote_count,                year: responseJson.release_date,                runtime: responseJson.runtime,                genre: responseJson.genres,                plot: responseJson.overview,            };            setMovie(movie);        })

But there is error on type.

My interface:

interface Movie {    id: number;    title: string;    backdrop: string;    note: number;    numberNote: number,    year: number,    runtime: number,    genre: {id: number, name: string}[],    plot: string}

according to this post : Set types on useState React Hook with TypeScript.

I can try to do something like that :

const [movie, setMovie] = useState<Movie>({id: 0,        title: "",        backdrop: "",        note: 0,        numberNote: 0,        year: 0,        runtime: 0,        genre: [{id: 0, name: ""}],        plot: ""});

But it doesn't look clean and I don't think this is the good solution to put random value in the first state.

setInterval not working with async funtion in react native

$
0
0

I am just learning to react native and I am trying to record video and show remaining video duration in the screen.

I am using the below code:

setInterval (() => {                    this.setState ({progress: progress * 2});                  }, 1000);                  var video = await this.camera.recordAsync ({                    mute: true,                    quality: '480p',                    maxDuration: this.state.max_duration,                  });

However video is recording perfectly fine, but setiInterval has stopped worked. How to run setInterval in a async funtion ? Please help..

Differing string values when passed between JavaScript (React Native) and Swift (via a Native module Objective-C definition)

$
0
0

I'm trying to send string data (specifically PEM formatted keys) out from a Native Module (written in Swift) through a Typescript exported function and into the main JS functions of a React Native app.

If I do an end-to-end test in Swift (converting the key data to strings, then to data and back again to simulate the transfer of the strings to and from JavaScript then all the logic works. I'm able to turn the data back into a key and use it to sign/encrypt. I've tried adjusting the encoding, using UTF8 and UTF16 strings but nothing seems to make it fail like it does when coming back into the native module.

The Typescript module definition

declare module 'encrypto' {  interface KeyPair {      publicKey: string;      privateKey: string;  }  export function generateKeys(keySize: number): Promise<KeyPair>;  export function getPublicKeyAsPEM(publicKey: string): Promise<string>;  export function encrypt(message: string, publicKeyAsPEM: string): Promise<string>;}export { Encrypto };export default Encrypto;

The Encrypto.m file

#import <React/RCTBridgeModule.h>@interface RCT_EXTERN_MODULE(Encrypto, NSObject)+ (BOOL)requiresMainQueueSetup {    return false;}RCT_EXTERN_METHOD(generateKeys:(int) keySize                  withResolver:(RCTPromiseResolveBlock) resolve                  withRejecter:(RCTPromiseRejectBlock) reject)RCT_EXTERN_METHOD(getPublicKeyPEM:(NSString) key                  withResolver:(RCTPromiseResolveBlock) resolve                  withRejecter:(RCTPromiseRejectBlock) reject)RCT_EXTERN_METHOD(encrypt:(NSString) message                  withPublicKeyAsPEM:(NSString) publicKeyAsPEM                  withResolver:(RCTPromiseResolveBlock) resolve                  withRejecter:(RCTPromiseRejectBlock) reject)@end

The Encryto.swift file

@objc(Encrypto)class Encrypto: NSObject {    @objc(generateKeys:withResolver:withRejecter:)    func generateKeys(keySize: Int,                      resolve: @escaping (RCTPromiseResolveBlock),                      reject:@escaping (RCTPromiseRejectBlock)) {        do {            let (publicKey, privateKey) = try .generateRSAKeys(keySize)            resolve([ "privateKey" : privateKey.base64EncodedString(),"publicKey" : publicKey.base64EncodedString() ])        } catch {            let error = error            reject("", "Key generation failed", error)        }    }    @objc(getPublicKeyPEM:withResolver:withRejecter:)    func getPublicKeyPEM(_ base64PublicKey: String,                         resolve: @escaping (RCTPromiseResolveBlock),                         reject: @escaping (RCTPromiseRejectBlock)) {        do {            guard let publicKeyData = Data(base64Encoded: base64PublicKey) else {                reject("", "Could not decode public key (is it Base64 encoded?)." ,NSError())                return            }            let pemFormattedPublicKey = try pemForPublicKey(publicKeyData)            resolve(pemFormattedPublicKey)        } catch {            let error = error            reject("", "Public Key PEM production failed", error)        }    }    @objc(encrypt:withPublicKeyAsPEM:withResolver:withRejecter:)    func encrypt(_ message:String,                 publicKeyAsPEM: String,                 resolve: @escaping (RCTPromiseResolveBlock),                 reject: @escaping (RCTPromiseRejectBlock)) {        do {            let publicKeyData = try publicKeyFromPEM(publicKeyAsPEM)            let encrypted = try encrypt(key, publicKeyData: publicKeyData)            resolve(encrypted)        } catch {            let error = error            reject("", "Encryption failed", error)        }    }}

If I log the PEM string in the Javascript, before it calls encrypt, I get this:

-----BEGIN RSA PRIVATE KEY-----MIIBCgKCAQEAqGloHcWKLYUGZZ4C2VsFNtFlMu1LgjbV7tHxwVGhNapz7YJASFqRhjAAOI68w4nKv/cq+rHsy7V4B7rCcttNAu0/fttvRrGpB4Yhh6EZQbSdoUasPSwg7d81kiipcs20CNr+b0SL4Ajb7ld5Sb9JRWnjfYHmh9DuKkcl+hzXKtejQuwvz/ZOzrdT+FJn1/tIKynv12li8JqoZwLaq3Glzu/ZwXYptg9E27v1Fj6+YbaFekrsM98dnt/RB6EkVqxhthIxjhYgCu9u56LZmUpa/ozSh+swpAR/xsewvcMX+geFMSklVgF04P2tEmJgz1bZjJ4OCa3zrezfLbmaKob65wIDAQAB-----END RSA PRIVATE KEY-----

and when I log the same string coming into the Swift function implementation I see this:

-----BEGIN RSA PRIVATE KEY-----MIIBCgKCAQEAqGloHcWKLYUGZZ4C2VsFNtFlMu1LgjbV7tHxwVGhNapz7YJASFqRhjAAOI68w4nKv/cq+rHsy7V4B7rCcttNAu0/fttvRrGpB4Yhh6EZQbSdoUasPSwg7d81kiipcs20CNr+b0SL4Ajb7ld5Sb9JRWnjfYHmh9DuKkcl+hzXKtejQuwvz/ZOzrdT+FJn1/tIKynv12li8JqoZwLaq3Glzu/ZwXYptg9E27v1Fj6+YbaFekrsM98dnt/RB6EkVqxhthIxjhYgCu9u56LZmUpa/ozSh+swpAR/xsewvcMX+geFMSklVgF04P2tEmJgz1bZjJ4OCa3zrezfLbmaKob65wIDAQAB-----END RSA PRIVATE KEY-----

and to make the calls into the Native module I'm simply doing...

  const keypair:KeyPair = await Encrypto.generateKeys(2048);  const publicKeyPem = await Encrypto.getPublicKeyPEM(keypair.publicKey);  const encryptedMessage = await Encrypto.encrypt("a message", publicKeyPem);

The getPublicKeyPEM function is able to successfully convert the key string passed in from Javascript and send back the resulting PEM string. But when that PEM string comes back for the subsequent encrypt call is is unable to successfully extract the key from it in order to perform the encrypt and despite both PEM files looking identical.

Does anyone have any ideas whats going on or what I could try please?

How to click on component behind the modal in react-native?

$
0
0

How to click on component behind the modal in react native? I am using native modal.Is there any prop for that?Thanks in advance

How to create specify typescript RN version?

$
0
0

I type the command to create React Native project with typescript.

npx react-native init MyApp --template react-native-template-typescript

package.json

"react-native": "0.63.2"

I want to create 0.62.2 with typescript so I try the command:

npx react-native init MyApp --version 0.62.2 --template react-native-template-typescript

package.json

"react-native": "0.63.0"

It is 0.63.0 not 0.62.2

Why I can't create 0.62.2 with typescript ?


How to trigger onPress in button tag embedded in TouchableOpacity tag without triggering onPress in TouchableOpacity

$
0
0

I have a view that stays hidden until the expand state is true. it is set to !expand in toggleView when TouchableOpacity is pressed. However, when i click on the buttons to add to cart & delete the view is also toggled.How can i prevent that from happening?

return (<View style={styles.accordion}>        {/* Visible Bar which is pressed to expand hidden view */}<TouchableOpacity onPress={toggleView} style={styles.collapsibleBar}><Icon name={expanded ? 'chevron-down-outline' : 'chevron-right-outline'} pack='eva' fill='grey' style={styles.icon} /><View style={styles.itemHeader}><View style={styles.itemHeaderTextView}>                {/* HEADER STUFF */}</View><View style={styles.buttonView}><Button onPress={() => addToCart()}>                Add to Cart</Button><Button onPress={() => delete()}>                delete</Button></View></View></TouchableOpacity>        {/* Hidden View */}<View style={{ maxHeight: height, width: '100%', alignSelf: 'center' }}><>            {console.log(expanded)}            {expanded && ExpandedChild({                setHeight: setHeight,                date: props.cargoCharge.storageDueDate, tableData: props.cargoCharge.charges            })}</></View></View>);

react navigation getparam with typescript

$
0
0

I am working on an app where I navigate from a FlatList to a custom component and I need to access the data i pass to the component. The FlatList component currently looks like this:

import React from 'react';import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';import Order from '../../components/Order/Order';import {    NavigationParams,    NavigationScreenProp,    NavigationState,} from 'react-navigation';export interface IProps {    navigation: NavigationScreenProp<NavigationState, NavigationParams>;}const OrdersOverview : React.FC<IProps> = props => {    const { navigation } = props;    return(<View><FlatList                keyExtractor={(item) => item.order_id}                data={orders}                renderItem={({ item }) => (<TouchableOpacity onPress= {() => {                        navigation.navigate('OrderDetails', item);                    }}><Order                            orderNumber={item.order_id}                            orderDate={item.orderDate}                            dueDate={item.dueDate}                            invoiceAmount={item.invoiceAmount}                            status={item.state}                            customer={item.customer}                        /></TouchableOpacity>                )}            /></View>    );}

I am trying to pass the item I clicked to a detail screen. However I cannot access the items and I don't know why it isn't working. I am trying to access the items like this:

import React, { useState } from 'react';import { View, Text, StyleSheet } from 'react-native';import {    NavigationParams,    NavigationScreenProp,    NavigationState,} from 'react-navigation';export interface IProps {    navigation: NavigationScreenProp<NavigationState, NavigationParams>;}const OrderDetails : React.FC<IProps> = (props) => {    const { navigation } = props;    const [categoryName, setCategoryName] = useState('information');    return(<View><Text>{ navigation.getParam('orderDate') }</Text></View>    );}

Why, even after specifying a type parameter for a React component, the linter still complains about '' missing in props validation?

$
0
0

Please consider the following TypeScript (.tsx) code:

import React from 'react';import { TextInputProps } from 'react-native';import { Container, TextInput, Icon } from './styles';interface InputProps extends TextInputProps {  name: string;  icon: string;}const Input: React.FC<InputProps> = ({ name, icon, ...props }) => (<Container><Icon name={icon} size={20} color="#666360" /><TextInput      keyboardAppearance="dark"      placeholderTextColor="#666360"      {...props}    /></Container>);export default Input;

By passing TextInputProps as a type parameter to React.FC I have access to the TextInput properties, which I'm destructuring in ...props. But I also need name and icon for other purposes, so I created an interface extending TextInputProps, specified these properties there, and passed InputProps to React.FC instead.

Now I get 'name' is missing in props validation - eslintreact/prop-types (same for 'icon'), but this didn't happen when I tried to get any of the properties specified inside TextInputProps.

Writing const Input: React.FC<InputProps> = ({ name, icon, ...props }: InputProps) => (/*...*/); makes the linter stop complaining, but I still don't get why using the type parameter doesn't. Can someone clarify this to me? Am I getting some concept wrong, or is it just a problem with the linter?

PS: I'm writing this on VS Code with ESLint extension.

PS2: This is the code inside styles.ts, if it may help:

import styled from 'styled-components/native';import FeatherIcon from 'react-native-vector-icons/Feather';export const Container = styled.View`  /* Some CSS */`;export const TextInput = styled.TextInput`  /* More CSS */`;export const Icon = styled(FeatherIcon)`  /* ... and CSS */`;

Ionic React - how to hide the Ion-Split-Pane when in the login and registration page

$
0
0

The main issue I am having is I don't know how to hide the IonSplitPane when I am not logged into the application. If anyone knows a solution to this issue it would be appreciated as the only answers online are done through Ionic Angular and not React with TypeScript.

Below is the app.tsx where the is placed.

import React, { useEffect, useState } from "react";import {  IonApp,  IonRouterOutlet,  IonSpinner,  IonSplitPane,} from "@ionic/react";import { Route, Redirect } from "react-router-dom";import { IonReactRouter } from "@ionic/react-router";import Filter from "./pages/Filter";import TabsMenu from "./pages/TabsMenu";import Home from "./pages/Home";import Login from "./pages/Login";import Register from "./pages/Register";/* Core CSS required for Ionic components to work properly */import "@ionic/react/css/core.css";/* Basic CSS for apps built with Ionic */import "@ionic/react/css/normalize.css";import "@ionic/react/css/structure.css";import "@ionic/react/css/typography.css";/* Optional CSS utils that can be commented out */import "@ionic/react/css/padding.css";import "@ionic/react/css/float-elements.css";import "@ionic/react/css/text-alignment.css";import "@ionic/react/css/text-transformation.css";import "@ionic/react/css/flex-utils.css";import "@ionic/react/css/display.css";/* Theme variables */import "./theme/variables.css";import "./theme/theme.css";import { getCurrentUser } from "./firebaseSetup";import { useDispatch } from "react-redux";import { setUserState } from "./redux/actions";import SideMenu from "./components/SideMenu";import ProfileContactsContextProvider from "./data/profileContactsContextProvider";import ProfileAboutsContextProvider from "./data/profileAboutsContextProvider";import ProfileEducationsContextProvider from "./data/profileEducationsContextProvider";import ProfileExperiencesContextProvider from "./data/profileExperiencesContextProvider";import ProfileInterestsContextProvider from "./data/profileInterestsContextProvider.tsxsContextProvider";import ProfileSkillsContextProvider from "./data/profileSkillsContextProvider";const RoutingSystem: React.FC = () => {  return (<IonReactRouter><IonSplitPane className="n" contentId="main"><SideMenu /><ProfileAboutsContextProvider><ProfileContactsContextProvider><ProfileEducationsContextProvider><ProfileExperiencesContextProvider><ProfileInterestsContextProvider><ProfileSkillsContextProvider><IonRouterOutlet id="main"><Route path="/" component={Home} exact /><Route path="/login" component={Login} exact /><Route path="/register" component={Register} exact /><Route path="/filter" exact><Filter /></Route><Route path="/tabs" exact><TabsMenu /></Route><Redirect to="/tabs" /></IonRouterOutlet></ProfileSkillsContextProvider></ProfileInterestsContextProvider></ProfileExperiencesContextProvider></ProfileEducationsContextProvider></ProfileContactsContextProvider></ProfileAboutsContextProvider></IonSplitPane></IonReactRouter>  );};const App: React.FC = () => {  const [busy, setBusy] = useState(true);  const dispatch = useDispatch();  useEffect(() => {    getCurrentUser().then((user: any) => {      console.log(user);      if (user) {        dispatch(setUserState(user.email));        window.history.replaceState({}, "/", "/tabs/newsfeed");      } else {        window.history.replaceState({}, "", "/");      }      setBusy(false);    });  }, []);  return (<IonApp>      {busy ? (<IonSpinner className="spinnerCenter" name="bubbles" color="primary" />      ) : (<RoutingSystem />      )}</IonApp>  );};export default App;

Here is the sideMenu component for the applcation.

import React from "react";import {  IonMenu,  IonHeader,  IonToolbar,  IonTitle,  IonContent,  IonItem,  IonIcon,  IonLabel,  IonToggle,} from "@ionic/react";import { moon, logoGithub } from "ionicons/icons";const SideMenu: React.FC = () => {  return (<IonMenu contentId="main"><IonHeader><IonToolbar><IonTitle>Opportunity</IonTitle></IonToolbar></IonHeader><IonContent><IonItem><IonIcon slot="start" icon={moon} /><IonLabel>Dark Mode</IonLabel><IonToggle            color="primary"            slot="end"            name="darkMode"            onIonChange={toggleDarkModeHandler}          /></IonItem><IonItem          button          href="https://github.com/ionic-team/ionic"          routerDirection="none"><IonIcon slot="start" icon={logoGithub} /><IonLabel>Github Repo</IonLabel></IonItem></IonContent></IonMenu>  );};const toggleDarkModeHandler = () => {  document.body.classList.toggle("dark");};export default SideMenu;

Here is the login.tsx page I also have a home.tsx and registrationpage which are similar which I can show if needed.

import React, { useState } from "react";import {  IonHeader,  IonContent,  IonToolbar,  IonTitle,  IonPage,  IonInput,  IonButton,  IonLoading,  IonButtons,  IonBackButton,} from "@ionic/react";import { Link, useHistory } from "react-router-dom";import { loginUser } from "../firebaseSetup";import { toast } from "../toast";import { setUserState } from "../redux/actions";import { useDispatch } from "react-redux";const Login: React.FC = () => {  const [busy, setBusy] = useState<boolean>(false);  const history = useHistory();  const dispatch = useDispatch();  const [username, setUsername] = useState("");  const [password, setPassword] = useState("");  async function login() {    setBusy(true);    const res: any = await loginUser(username, password);    if (res) {      console.log(res);      dispatch(setUserState(res.user.email));      history.replace("/tabs/newsfeed");      toast("You have logged in!");    }    setBusy(false);  }  return (<IonPage><IonHeader><IonToolbar><IonButtons slot="start"><IonBackButton defaultHref="/" /></IonButtons><IonTitle>Login</IonTitle></IonToolbar></IonHeader><IonLoading message="Please wait.." duration={0} isOpen={busy} /><IonContent className="ion-padding"><IonInput          placeholder="Email?"          onIonChange={(e: any) => setUsername(e.target.value)}        /><IonInput          type="password"          placeholder="Password?"          onIonChange={(e: any) => setPassword(e.target.value)}        /><IonButton onClick={login}>Login</IonButton><p>          New to Opportunity? <Link to="/register">Register</Link></p></IonContent></IonPage>  );};export default Login;

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

$
0
0

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

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

This is my config-overrides.js

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

Package.json:

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

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

Hence, I installed

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

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

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

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

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

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

I want to do something like this:

import {ResultAlert} from '~/components';

React Native Project BUILDS Succesfull(with deprecated warning) and opens in my emulator, but keeps loading forever

$
0
0

I used yarn to install the packages, Im using typescript, my index is JS.I'm getting a white screen with the load symbol on the emulator..Thanks for the ones helping

Here's what Im getting:

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. (node:41396) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency(Use `node --trace-warnings ...` to show where the warning was created)Jetifier found 1123 file(s) to forward-jetify. Using 4 workers...info JS server already running.info Installing the app...> Task :app:installDebug09:49:22 V/ddms: execute: running am get-config09:49:22 V/ddms: execute 'am get-config' on 'emulator-5554' : EOF hit. Read: -109:49:22 V/ddms: execute: returningInstalling APK 'app-debug.apk' on 'Pixel_2_API_28(AVD) - 9' for app:debug09:49:22 D/app-debug.apk: Uploading app-debug.apk onto device 'emulator-5554'09:49:22 D/Device: Uploading file onto device 'emulator-5554'09:49:22 D/ddms: Reading file permision of C:\Users\Daniel\CalcSol\android\app\build\outputs\apk\debug\app-debug.apk as: rwx------09:49:22 V/ddms: execute: running pm install -r -t "/data/local/tmp/app-debug.apk"09:49:24 V/ddms: execute 'pm install -r -t "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -109:49:24 V/ddms: execute: returning09:49:24 V/ddms: execute: running rm "/data/local/tmp/app-debug.apk"09:49:24 V/ddms: execute 'rm "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -109:49:24 V/ddms: execute: returningInstalled on 1 device.Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.Use '--warning-mode all' to show the individual deprecation warnings.See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings        BUILD SUCCESSFUL in 29s141 actionable tasks: 2 executed, 139 up-to-dateinfo Connecting to the development server...info Starting the app on "emulator-5554"...Starting: Intent { cmp=com.calcsol/.MainActivity }'''

How to add items in array in react native?

$
0
0

I want to add item.name,item.id,item.price in array onClick of button.Button is in Flatlist so every time I eant to save these items in array and finally I want all these items.

**enter code here**import React, { Component } from 'react';import {Text,View,FlatList, Modal,TouchableOpacity} from 'react-native';import { Style } from './style';import CustomButton from '../../custom-button/custom-button';import { SafeAreaView } from 'react-native-safe-area-context';import ModalComponent from '../Modal/ModalComponent';import CustomIcon from '../CustomIcons/CustomIcon';interface MenuItemsProps{  menuArray:any[];  category_name:string;}interface MenuItemsState{  flag:number;  visible:boolean;  firstModalVisible2:boolean;  firstModalVisible3:boolean;  itemcount:number;  cartArray:any[];// I want to add items in this array}export default class MenuItemsComponent extends Component<MenuItemsProps,MenuItemsState>{    constructor(props:MenuItemsProps){        super(props);        this.state={          flag:0,          visible:false,          firstModalVisible2:false,          firstModalVisible3:false,          itemcount:0,          cartArray:[]        }    }    componentDidMount(){      {this.props.menuArray.map((data) => {          {if(this.props.category_name==data.category_name)            this.setState({              flag:this.state.flag+1            })}}        )}         }    render(){    return (<SafeAreaView style={Style.paddingStyle}>            {this.state.flag!=0?<View><Text style={Style.textStyle}>{this.props.category_name}</Text> <FlatList              data={this.props.menuArray}              renderItem={({item}) =>(<View>                  {item.category_name==this.props.category_name?<View style={{paddingTop:7}}> <View  style={Style.menu_buttonStyle}>        <View><Text style={Style.nameStyle}>{item.name}</Text><Text style={Style.priceStyle}>{'\u20B9'}{item.price}</Text></View><View><CustomButton //onthis button click                          onPress={()=>                              this.setState({itemcount:this.state.itemcount+1})                          }                           text=" Add " outline={true} />                          {/* {this.state.visible&& <ModalComponent  price={item.price} visible={this.state.visible} itemname={item.name}/> } */}</View></View><Text style={Style.descriptionStyle}>{item.description}</Text></View>:null}</View>              )}              keyExtractor={item => item.id}            /></View>:null} </SafeAreaView>    );  }}

This is my code

I want to add item.name,item.id,item.price in array onClick of button.Button is in Flatlist so every time I eant to save these items in array and finally I want all these items.


Can't tap on checkboxes in React Native

$
0
0

I make tests on React Native. I use react-native-paper for this. This is my code:

{(!props.question.isSingleAnswer && props.question.answers.length) && <View>          {props.question.answers.map((item) => (<List.Item                 key={item.id.toString()}                 title={item.title}                 left={checkProps => <Checkbox {...checkProps} status='unchecked' onPress={() => addAnswer(props.question, item)}/>}             />          ))}</View>}

But I can't check checkboxes. The same problem with radio buttons.

Why does it happen and how can I fix it?

UPD: the problem was solved. Question is closed.

Validation functions with react

$
0
0

I am trying with React to do a validation, with a footer which has several buttons, then each one has its value (home, orders, payments, among others), I want that when it is located in one of them, it will be check (I already have that in css), I have not managed to make the correct setState to achieve it.

interface State {  value: any,  isActive: boolean}class Footer extends React.PureComponent<Props, State>{  state: State = {    value: '',    isActive: false  }  render() {    const { isActive } = this.state    return (<IonFooter><div className="footer-menu-home"><button value="home" onClick={() => this.props.history.push('/home')}>            {isActive && (<div><img src={iconHomeActive} alt="" /></div>            )}            {!isActive && (<div><img src={iconHomeInactive} alt="" /></div>            )}          ...</button> <button onClick={() =>this.props.history.push('/orders')} ><div><img src={iconOrderInactive} alt="" /></div>              Orders</button></div></IonFooter>        );  }}

Basically, when he's on any of those, show him as active, only where he's standingI don't know how to tell it or how to make the example stand on orders take the value of the property that I pass by button

Errors after adding typescript to react native app

$
0
0

I'm very new to TypeSccript. I'm trying to convert my React Native to use TypeScript. I followed the instructions here: https://reactnative.dev/docs/typescript

After running yarn tsc I get errors like:

node_modules/@react-navigation/stack/lib/typescript/src/types.d.ts:99:67 - error TS2339: Property 'style' does not exist on type 'PropsWithChildren<AnimatedProps<TextProps & RefAttributes<Text>>>'.99     headerTitleStyle?: React.ComponentProps<typeof Animated.Text>['style'];

Is this an error in the node module or in my own code? Any tips on what I need to do?

I have a minimal project here:https://github.com/jauggy/React-Native-TypeScript-Test

Typing incompatibility between useRef() and d3.drag() in React-native

$
0
0

I have a weird typing issue that's been driving me crazy for the last two days. I hope you can save my sanity :D!

Stack : react-native (Functional Component oriented) + typescriptLibs involved: react-native-svg, d3

I would like to create a "DraggableCircle" Component that extends the Component Circle from react-native-svg. I chose to use d3 instead of PanResponder because I already knew a bit about the lib.

Here is my code:

import React, { useEffect, useRef, Component } from 'react';import { Circle, CircleProps } from 'react-native-svg';import * as d3 from 'd3';type IProps = CircleProps;const DraggableCircle: React.FC<IProps> = (props: IProps) => {  const circleRef = useRef(null);  useEffect(() => {    if (circleRef.current) {      const circle = d3.select(circleRef.current);      circle.call(        d3.drag().on('start', () => {          console.log('ok');        }),      );    }  }, [circleRef]);  return <Circle {...props} ref={circleRef} />;};export default DraggableCircle;

What I see :Screen capture of the error

I use eslint which allows me to catch errors. Eslint indicates an error in d3.drag() :Type 'Selection<null, unknown, null, undefined>' is not assignable to type 'Selection<Element, unknown, any, any>'.

So I understand that I have to type useRef() so that it considers the element that will be referenced not as null, but as an Element.

What I've tried:const circleRef = useRef<SVGCircleElement>(null);const circleRef = useRef<CircleProps>(null);const circleRef = useRef<Element>(null);

With each of these three typings, I have no more errors on the d3.drag().On the other hand, I have a new typing error on ref={circleRef} :Type 'RefObject' is not assignable to type 'RefObject<Component<CircleProps, any, any>>>'.

What I've tried:const circleRef = useRef<Component<CircleProps>>(null);

This removes the error on the ref, but I immediately find the error on the d3.drag() (which makes sense to me...)So I have the impression that the types expected by d3.drag() and by ref are incompatible. After a lot of searching I couldn't find any help in this sense. It seems that most people don't have this problem.

Any idea?=> If you have a completely different solution to propose to create a draggable element, I'm interested too, even if I'd like to avoid turning to PanResponder which doesn't seem to be easy to understand.

Thank you in advance.

toggle-switch-react-native for typescript

$
0
0

I want to use the toggle-switch-react-native component in my Typescript app. I tried installing it like this:

yarn add toggle-switch-react-native --save
@types/toggle-switch-react-native

However, I still get an error that:

Could not find a declaration file for module 'toggle-switch-react-native'. '/Users/grannyandsmith/insta/app/node_modules/toggle-switch-react-native/ToggleSwitch.js' implicitly has an 'any' type.  Try `npm install @types/toggle-switch-react-native` if it exists or add a new declaration (.d.ts) file containing `declare module 'toggle-switch-react-native';`

How can I define its types? Is there an alternate? Am I installing it correctly?

Viewing all 6215 articles
Browse latest View live