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

How to keep marker at the bottom of the screen when zooming like google maps?

$
0
0

I was wondering if it is possible to change the default behavior zoom, the default seems to change the viewport in all directions, but I want to keep the bottom where it is, and only resize the other three, pitch is also necessary.

enter image description hereenter image description here

I want the marker to keep it's position when zooming in/out like in first gif.

The way it works right now is when the gesture stops, the camera animates to new marker that gets generated because, the camera for some reason does not update while user is zooming.

const markerLatLng: LatLng = {latitude: 42.00352792344026, longitude: 21.396884999999997}const generatedMarker: LatLng = computeDestinationPoint(  markerLatLng,  currentDistance,  currentHeading,);
mapViewRef.current?.animateCamera(  {    center: generatedMarker,    heading: currentHeading,    pitch: defaultPitch,    zoom: currentZoom,  })

Image type in typescript

$
0
0

Hello guys what should be the type of Source and Style

The source is going to contain the image file location. Something like this

source = require('../../../assets/user.png')

and style is going to have an Object of styles but not sure if I write style: Object will be right.

export interface AvatarProps {    source?: any;  <<<<< Don't want to use any    style?: any;   <<<<< Don't want to use any    shape?: string;    ImageComponent?: React.ComponentType;    size?: 'tiny' | 'small' | 'medium' | 'large' | 'giant';}export const Avatar: FunctionComponent<AvatarProps> = ({    shape,    style,    size = 'medium',    ImageComponent,    source = require('../../../assets/user.png'),}) => {    return (<View>         ....</View>    );};

This expression is not callable. Not all constituents of type 'string | ((searchTerm: string) => Promise) | []' are callable

$
0
0

I have my custom useResults hook like this

import { useEffect, useState } from 'react';import yelp from '../api/yelp';export default () => {  const [results, setResults] = useState([]);  const [errorMessage, setErrorMessage] = useState('');  const searchApi = async (searchTerm:string) => {    console.log('Hi there!');    try {      const response = await yelp.get('/search', {        params: {          limit: 50,          term: searchTerm,          location: 'san jose'        }      });      setResults(response.data.businesses);    } catch (err) {      setErrorMessage('Something went wrong');    }  };  useEffect(() => {    searchApi('pasta');  }, []);  return [searchApi, results, errorMessage];};

in my Search screen I import my custom hook and do a destructuring like this

const [searchApi, errorMessage, results ] = useResults();

But I can't call my searchApi method from JSX code like below (I can call errorMessage and results).

<SearchBar term={term} onTermChange={setTerm} onTermSubmit={()=>searchApi(term)}/>

I'm getting this error

This expression is not callable.Not all constituents of type 'string | ((searchTerm: string) => Promise) | never[]' are callable.Type 'string' has no call signatures

How to pass the "searchApi" function to "onTermSubmit" prop in my "SearchBar" component ?as you can see "searchApi" is an async function

Below is my 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.10","@types/axios": "^0.14.0","axios": "^0.21.1","expo": "~40.0.0","expo-status-bar": "~1.0.3","react": "16.13.1","react-dom": "16.13.1","react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz","react-native-gesture-handler": "~1.8.0","react-native-reanimated": "~1.13.0","react-native-safe-area-context": "3.1.9","react-native-screens": "~2.15.0","react-native-web": "~0.13.12","react-navigation": "^4.4.3","react-navigation-stack": "^2.10.2"  },"devDependencies": {"@babel/core": "~7.9.0","@types/react": "~16.9.35","@types/react-dom": "~16.9.8","@types/react-native": "~0.63.2","typescript": "~4.0.0"  },"private": true}

Below is my tsconfig.json

{"compilerOptions": {"allowSyntheticDefaultImports": true,"jsx": "react-native","lib": ["dom", "esnext"],"moduleResolution": "node","noEmit": true,"skipLibCheck": true,"resolveJsonModule": true,"strict": true  }}

enter image description here

Error app.default.object is not a function

$
0
0

I am new to react-native and I'm trying to help on a project. I started by refactoring the code to have a better file structure. I implemented the barrels and added the path aliases (module resolver).Everything works fine in vscode but when I run on android, it gives me this error:

TypeError:_app.default.objects is not a function. {...} _app.default.objects is undefined.

Here is my tsconfig:

"baseUrl": ".","paths": {"@assets/*": ["./app/assets/*"],"@components/*": ["./app/components/*"],"@components": ["./app/components"],"@containers/*": ["./app/containers/*"],"@db": ["./app/db"],"@db/*": ["./app/db/*"],"@languages/*": ["./app/languages/*"],"@navigation/*": ["./app/navigation/*"],"@styles/*": ["./app/styles/*"],"@services": ["./app/services"],"@services/*": ["./app/services/*"],"@utils": ["./app/utils"],"@utils/*": ["./app/utils/*"],    }

And my babel-config:

  plugins: [    ['module-resolver',      {        root: ['./app'],        extensions: ['.ios.js', '.android.js', '.js', '.json', '.ts', '.tsx'],        alias: {'@languages': './app/languages','@db': './app/db','@styles': './app/styles','@services': './app/services','@utils': './app/utils','@assets': './app/assets','@navigation': './app/navigation','@components': './app/components','@containers': './app/containers',        },      },    ],  ]

It raises the error each time I use the db:Here is my import:

import { Song } from '@db'import { GlobalSettings } from "@db/GlobalSettings";

also if I use something like that:

const [songs, setSongs] = useState(Song.getAll())

but it's the same with everything else from the db directory.

Thanks!

Jest cannot find module @env React Native

$
0
0

I'm currently facing some problem I'm using in my react native app https://github.com/goatandsheep/react-native-dotenv for handling .env.

Error => Cannot find module '@env' from 'src/api/api.ts'

I'm testing currently my redux saga to call the api endpoint:

import axios from 'axios';import {API_URL} from '@env';export default axios.create({  baseURL: API_URL,  responseType: 'json',});

API Endpoint

export const sendCheckNumber = async (  phoneNumber: string,): Promise<AuthenticationTO> => {  const response = await axios.get<AuthenticationTO>(    `SendCheckNumber/${phoneNumber}`,  );  return response.data;};

I'm using ts-jest package.json. I saw in the docs its possible to include bable in ts-jest because I'm using bable to import the 'module:react-native-dotenv', as plugin. I thought that will already solve my problem but unfortunately it still fails. Maybe someone of you have some suggestion what could cause this error.

Thank you!!!

package.json

"jest": {"preset": "react-native","transform": {"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js","\\.(ts|tsx)$": "ts-jest"    },"globals": {"ts-jest": {"babelConfig": "babel.config.js","tsConfig": "tsconfig.jest.json"      }    },"moduleFileExtensions": ["ts","tsx","js"    ],"modulePaths": ["<rootDir>/src"    ],"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"  }

How to redefine type for React class prop

$
0
0

I´m using Avatar from react-native-elements and the ImageComponent prop is typed as React.ComponentClass (IntelliSense report type React.ComponentClass<{}, any>)

When using a functional component (with prop key) I get red squiggles under ImageComponent:

<Avatar    rounded    size={c.styles.avatarSize}    containerStyle={{ margin: c.styles.marginLRTB / 2 }}    placeholderStyle={{ backgroundColor: colors.background }}    ImageComponent={() => AvatarImage(key)}  />

Type '() => JSX.Element' is not assignable to type 'ComponentClass<{}, any>'.ts(2769)

AvatarImage:

  const AvatarImage = (key: string) => (<FastImage      style={{ width: '100%', height: '100%' }}      source={sourcesState[key].category === 'In-app' ? avatars[key as QuotesListKeys] : { uri: sourcesState[key].imageUrl }}    />  );

How can I fix this typescript error?

I´ve tried to define a new class/interface that extend Avatar/AvatarProps:

  type MyAvatarProps = Omit<AvatarProps, 'ImageComponent'> & { ImageComponent: FC<{ key: string }> };  class MyAvatar extends Avatar<MyAvatarProps> {}

I get typescript error Type 'Avatar' is not generic.ts(2315)

How do I extend Avatar with MyAvatarProps when it's not generic?

Or is there other/better ways to handle this?

Update:

See my answer below

React Native Paper the List.Accordion I can put the Icon

$
0
0

Objective

I am using the library react-native-paper and I am using the List components, but in the List.Accordion appears one strange image at the right position, I would like to put an icon arrow down in the place. But the List.Accordion just receive the left prop and no the right prop.

{bleDevices.length > 0 && (<List.Section><List.Accordion              title="Dispositivos encontrados"              left={props => <Icon name="arrow-down" size={24} />}>              {_.map(bleDevices, (device, index) => (<List.Item                  key={index}                  title={`${device.name || 'device'} (${device.rssi}) `}                  description={`${device.localName} (${device.id})`}                  right={props => (<Button onPress={toggleConnectDevice(device.name)}>                      Conectar</Button>                  )}                />              ))}</List.Accordion></List.Section>        )}

Image

enter image description here

How to remove a text from the StatusBar using React-Native?

$
0
0

I have a problem with this code:

<Tab.Navigator      shifting={false}      barStyle={{        backgroundColor: home ? '#000' : '#fff',      }}      initialRouteName="Home"      activeColor={home ? '#fff' : '#000'}><Tab.Screen        name="Home"        component={Home}        listeners={{          focus: () => setHome(true),          blur: () => setHome(false),        }}        options={{          tabBarLabel: 'Home',          tabBarIcon: ({ color }) => (<FontAwesome name="home" size={24} color={color} />          ),        }}      /><Tab.Screen        name="Discover"        component={Discover}        options={{          tabBarLabel: 'Discover',          tabBarIcon: ({ color }) => (<AntDesign name="search1" size={24} color={color} />          ),        }}      />

I try to remove the name "Home" and "Discover". I just want to see the icon. If I remove tabBarLabel: 'Discover', nothing happens, but if I try this : tabBarLabel: '', does not show up anymore, instead I have a space there


React Native useRef with custom TextInput and TypeScript

$
0
0

I am getting the following warning on my custom input component:

'TextInput' refers to a value, but is being used as a type here. Did you mean 'typeof TextInput'?

When referencing it using useRef like so:

const lastNameRef = useRef<TextInput>(null)

Here's what TextInput looks like:

import React, { forwardRef } from "react"import {  TextInput as ReactTextInput,  TextInputProps as ReactTextInputProps,} from "react-native"import styled from "styled-components/native"import {  compose,  space,  SpaceProps,  color,  ColorProps,  layout,  LayoutProps,  flexbox,  FlexboxProps,  border,  BorderProps,  position,  PositionProps,  background,  BackgroundProps,  typography,  TypographyProps,} from "styled-system"export type TextInputProps = ReactTextInputProps &  SpaceProps &  ColorProps &  LayoutProps &  FlexboxProps &  BorderProps &  PositionProps &  BackgroundProps &  TypographyPropsconst StyledTextInput = styled.TextInput<TextInputProps>`  ${compose(    space,    color,    layout,    flexbox,    border,    position,    background,    typography,  )};`export const TextInput = forwardRef<ReactTextInput, TextInputProps>(  (    {      fontFamily = "body",      fontWeight = "regular",      fontSize = 1,      color = "text",      ...rest    },    ref,  ) => {    return (<StyledTextInput        {...{ ref, fontFamily, fontWeight, fontSize, color, ...rest }}      />    )  },)

I am forwarding the reference, which is what should get rid of that warning.

Any suggestions?

How to avoid Typescript Object is possibly 'null'. TS2531

$
0
0

I am trying to get the scroll position using the following code:

    useEffect (()=>{    document.addEventListener("scroll", e => {        let scrolled = document.scrollingElement.scrollTop;        if (scrolled >= 5){           setPos("moved")        } else {           setPos("top")        }    })  },[])

Typescript complains about the document.scrollingElement.scrollTop saying that it is possibly null. How do I avoid this error and keep typescript happy?

Const variable as type - Typescript

$
0
0

During learning Typescript I faced problem when I used constant variable with the value of action which I use to reducer (created to prevent typo - I have read somewhere it is good practice).

const INPUT_CHANGE: string = "INPUT_CHANGE";const INPUT_BLUR: string = "INPUT_BLUR";

I also have created type to define reducer action:

type InputReducerAction =  | { type: INPUT_CHANGE; value: string; isValid: boolean }  | { type: INPUT_BLUR };

And here is my reducer:

const inputReducer = (state: InputReducerState, action: InputReducerAction) => {  switch (action.type) {    case INPUT_CHANGE:      return {        ...state,        value: action.value,        isValid: action.isValid,      };    case INPUT_BLUR:      return {        ...state,        touched: true,      };    default:      return state;  }};

When I have everythink like above INPUT_CHANGE and INPUT_BLUR in InputReducerAction are marked as error:

'INPUT_CHANGE' refers to a value, but is being used as a type here. Did you mean 'typeof INPUT_CHANGE'?ts(2749)

'INPUT_BLUR' refers to a value, but is being used as a type here. Did you mean 'typeof INPUT_BLUR'?ts(2749)

Problem disappear when I use double quotes for this constants, like so

type InputReducerAction =  | { type: "INPUT_CHANGE"; value: string; isValid: boolean }  | { type: "INPUT_BLUR" };

But my const variables are useless right now. What I have done wrong or missed?

During writing this question I got idea to use enum:

enum INPUT_ACTION {  INPUT_CHANGE = "INPUT_CHANGE",  INPUT_BLUR = "INPUT_BLUR"}type InputReducerAction =  | { type: INPUT_ACTION.INPUT_CHANGE; value: string; isValid: boolean }  | { type: INPUT_ACTION.INPUT_BLUR };const inputReducer = (state: InputReducerState, action: InputReducerAction) => {  switch (action.type) {    case INPUT_ACTION.INPUT_CHANGE:      return {        ...state,        value: action.value,        isValid: action.isValid,      };    case INPUT_ACTION.INPUT_BLUR:      return {        ...state,        touched: true,      };    default:      return state;  }};

and using it in reducer and type. Errors disappear BUT is it good idea or can I do this in a better way

map function in React-Native

$
0
0

I am new to React Native and I am using Typescript for my project. I am difficulty to do mapping in React Native. Below is my code for interface:

interface Teacher {  name: string;  sex: string;  age: number;  student: Student[];}interface Student {  name: string;  sex: string;  address: string;}

I don't have any problem mapping Teacher's interface but I am having difficulty on how to map Student interface when I use the map function in my code.

{Class.map(class => (<View>      {class.student.map(class => (<Text>{class.name}</Text>      ))}      {class.student.map(class => (<Text>{class.sex}</Text>      ))}      {class.student.map(class => (<Text>{class.address}</Text>      ))}</View>)}

When I did my coding like this, I get an error Cannot read property 'map' of undefined in my console. Thank you in advance.

I need to create a Dropdown submenu in React Native

$
0
0

Dropdown submenu react native

Hi guys, i need to create a dropdown submenu in react native.

Right now, i'm using typescript in my proyect and react navigation and i can't find any updated and correct solution for this issue.

I need to create this solution in typescript only.

Can't change or use properties from imported TextInput in React Native

$
0
0

I was trying to use a created TextField component inside Formik, I created my own TextField component called Input and imported inside the form, but I cant change any of it's props or call it's methods, like style or onChangeText, any method I try to use with onChangeText won't work, for example. Here's my code from the component and the formulary.

Here's the code of my Input Component and the form where I import it to:

// Input Componentimport React, { useState } from 'react';import { TextInput, TextInputProps } from 'react-native';import styles from '../../styles/styles';interface InputProps extends TextInputProps{    value: string,}const Input: React.FC<InputProps> = ({value, ...rest}) => {    const [color, setColor] = useState("#f2f2f2");    return (<TextInput            onFocus={() => setColor('#f9ffc4')}            onBlur={() => setColor('#f2f2f2')}            style={{                width: "70%",                minHeight: 40,                borderColor: styles.primaryColor,                borderBottomWidth: 1,                padding: 0,                borderRadius: 5,                marginBottom: 5,                backgroundColor: color,            }}></TextInput>    )}export default Input; // Form Pageimport React from 'react';import { Button, TextInput, View } from 'react-native';import { Formik } from 'formik'import Input from '../../../components/inputs/Input';export default function FormikTest({ }) {    return (<Formik                initialValues={{ input: '', teste: '' }}                onSubmit={values => console.log(values)}>                {({ handleChange, handleSubmit, values }) => (<View style={{ padding: 8, alignItems: 'center' }}><TextInput                            style={{                                margin: 10,                                width: '50%',                                height: 50,                                borderWidth: 1,                                borderColor: '#000',                            }}                            onChangeText={handleChange('input')}                            value={values.input}                        /><Input                            onChangeText={() => { console.log('aqui') }}                            value={values.teste}                        /><Button onPress={handleSubmit} title="Submit" /></View>                )}</Formik>    )}

How to access Enum in typescript ? giving error "Element implicitly has an any type because index expression is not of type number"

$
0
0
export enum r {  color1 = "Red"  color2 = "green"  color3 = "blue"}ar = ["color1", "color2"];ar.map(e => {  if (r[e as any] !== undefined) {    return r[e]  }})

Above statement giving "Element implicitly has an any type because index expression is not of type number"


How to check type in react-native?

$
0
0

I have a problem, already solved it, but make me confuse about modules.

I tried to import an Animated in my component.

import { Animated, Easing } from 'react-native';

and then, I tried to find Its type (flow), I found that answer in.Flow types for react-native's Animated library (Thank you).

import type AnimatedValue from 'react-native/Libraries/Animated/src/nodes/AnimatedValue';

The question is.When I open Animated in import { Animated, Easing } from 'react-native';(right click, then I go to type definition with "Visual code"), Why it doesn't go to Its module, but to this path? (Library/Caches)enter image description hereI tried to find out this file (index.d.ts) in "react-native" modules, but I cant find it. Why?

Then I try to read index.d.ts, to find out type for Animated.Value.

export namespace Animated {    type AnimatedValue = Value;    type AnimatedValueXY = ValueXY;export class Value extends AnimatedWithChildren {

Horraay, I got Animated.Value is a class, and Its type is an AnimatedValue. Then as usual to find Its path, I right click, then I go to type definition with "Visual code", but I found nothing.

So, how can this import type AnimatedValue from 'react-native/Libraries/Animated/src/nodes/AnimatedValue relate to type AnimatedValue = Value; in index.d.ts?

"react-native": "0.63.2",

How do I configure absolute paths for imports in TypeScript based React Native apps?

$
0
0

In order to avoid '../../../../' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instead.

It is important that the configuration also supports Jest unit tests.

I created the app using npx react-native init MyTestApp --template typescript

React Native version: 0.60.5

What is the exact configuration I would need to achieve this?

Navigation.navigate is not a function , navigation is underfined

$
0
0

i have a problem , in React-Native.Can someone help me

<Button title="Save" onPress = {() => navigation.navigate('Save' , { image })}/>    {image && <Image source = {{uri: image}} style= {{flex: 1}}/>}</View>  );}

i got a error: navigation.navigate is not a function. (In 'navigation.navigate('Save', {image: image})', 'navigation.navigate' is undefined)

Navigation.navigate is not a function, navigation is undefined

$
0
0

I have a problem, in React-Native.

<Button title="Save" onPress = {() => navigation.navigate('Save' , { image })}/>    {image && <Image source = {{uri: image}} style= {{flex: 1}}/>}</View>  );}

I got an error:

navigation.navigate is not a function. (In 'navigation.navigate('Save', {image: image})', 'navigation.navigate' is undefined)

React / TypeScript error when updating array using setState()

$
0
0

I am looking to modify a property of one of the items in the array using the updater returned from setState. The function is passed as props to the child, who then call this with their own index to change their status.

  const tryMarkHabitAsComplete = (index: number) => {    let list: HabitType[] = [...habitList];    let habit = {      ...list[index],      isComplete: true,    };    list[index] = habit;    setHabitList({list});  };

When running withsetHabitList(list); the array gets cleared and becomes undefined, so I am unable to use it after I call this function once.

The error that keeps appearing is:

Argument of type '{ list: HabitType[]; }' is not assignable to parameter of type 'SetStateAction<HabitType[]>'. Object literal may only specify known properties, and 'list' does not exist in type 'SetStateAction<HabitType[]>'

I am treating the state as immutable and attempting (I think) to set the state. When debugging, everytime I click I empty the array for my habitsList. Further up, I define the state as:

const [habitList, setHabitList] = useState<HabitType[]>([]);

If I try to setState in other ways, the array becomes undefined or blank and loses information. I should clarify, this is a side project written w/ react-native.

MRE Edit:

2 components in a react-native app, discarding css & irrelevant imports:Chain.tsx

export type HabitType = {  text: string;  index: number;  isComplete: boolean;  tryMarkHabit: (index: number) => void;};const Chain = (props: any) => {  const [habitList, setHabitList] = useState<HabitType[]>([]);  // Set the initial state once w/ dummy values  useEffect(() => {    setHabitList([      {        text: "1",        index: 0,        isComplete: false,        tryMarkHabit: tryMarkHabitAsComplete,      },      {        text: "2",        index: 1,        isComplete: false,        tryMarkHabit: tryMarkHabitAsComplete,      }    ]);  }, []);  // Only is previous item is complete, let habit be marked as complete  const tryMarkHabitAsComplete = (index: number) => {    let list: HabitType[] = [...habitList];    let habit = {      ...list[index],      isComplete: true,    };    list[index] = habit;    setHabitList(list);  };  let habitKeyCount = 0;  return (<View style={styles.container}>      {habitList.map((habit) => (<Habit key={habitKeyCount++} {...habit} />      ))}</View>  );};export default Chain;

Habit.tsx

import { HabitType } from "./Chain";const Habit = ({ text, index, isComplete, tryMarkHabit }: HabitType) => {  const [complete, setComplete] = useState<boolean>(false);  return (<TouchableOpacity      style={complete ? styles.completeHabit : styles.uncompleteHabit}      onPress={() => tryMarkHabit(index)}><Text style={styles.chainText}>{text}</Text></TouchableOpacity>  );};export default Habit;

When I press a habit, it calls tryMarkHabitAsComplete successfully, however it appears to clear the array - the array afterwards becomes undefined as far as I can tell.

Viewing all 6287 articles
Browse latest View live


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