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

Typescript optional chaining error: Expression expected.ts(1109)

$
0
0

I am trying to do optional chaining in Typescript + React Native.

Let's say I have the following interfaces:

interface Bar {  y: number}interface Foo {  x?: Bar}

and I try to run the following:

 const test: Foo = {x: {y: 3}}; console.log(test.x?.y);

VSCode will show an error under the ?. saying the following: Expression expected.ts(1109)

Do you have any idea why this is happening or how should I fix it? Thanks.


TS, React Native | Converting string to date gives NaN but works on console [duplicate]

$
0
0

Facing a strange issue wherein my react-native (with TypeScript) returns NaN for the following snippet but it works when I run the same snippet on a JS/TS console

const convertDateStringToSlotString = (date: string): string => {  var dateObject = new Date(date);  return `${dateObject.getHours()}:${dateObject.getMinutes()}`;};

Also tried logging dateObject and it returns Date { NaN }

Example string I am passing -> "2020-08-02 11:00:00+00"

TypeError: _fieldRef$current.blur is not a function

$
0
0

I used useRef& ref for a custom FieldInput component that contains <Input> from Native Base.

const fieldRef = useRef();...    const handleSubmitForm = (    values: FormValues,    helpers: FormikHelpers<FormValues>,  ) => { ....    fieldRef.current.blur();    helpers.resetForm();  };

However, I was getting an error on fieldRef.current that Object is possibly 'undefined'.. So, I changed it like this:

const fieldRef = useRef<any>(null);
fieldRef.current?.blur();

This fixed the inline error but upon submitting the form, I still get this:

Warning: An unhandled error was caught from submitForm() TypeError: _fieldRef$current.blur is not a function

How can I fix this? Any workaround would help. I just want to remove the warning.

codesandbox: https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

React Native: When I add isSignedIn ternary operator statement on React.Navigator, it is saying that I sent an object as react child

$
0
0

I started learning React Native and doing something basic from React but it doesn't work and I can't find the problem.

This is my code, and this is the error I get.

It worked until I added the ternary statement, which should return only the screens for logged/unlogged users.

Do someone know what I did wrong or what should I do? Thank you!

can't type in Input field after changing onChangeText

$
0
0

I have a custom FieldInput icon where I use Native Base's input component. I use it for validation with Formik. When I use it like this:

 onChangeText={handleChange(fieldType)}

everything seems to work fine but I get an error on onChangeText that

  Overload 1 of 2, '(props: Readonly<Input>): Input', gave the following error.    Type 'void' is not assignable to type '((text: string) => void) | undefined'.

When I change it to

 onChangeText={()=>handleChange(fieldType)}

the error is gone but then my input field stops working. I can no longer type into it. What am I doing wrong? My component looks like this:

type FieldInputProps = React.PropsWithRef<{  handleChange: (e: string) => void;  value: string;  fieldType: string;  placeholderText?: string;  style?: object;  rounded?: boolean;}>;export const FieldInput = React.forwardRef<Input, FieldInputProps>(({  handleChange,  fieldType,  placeholderText,  value,  style,  rounded,}, ref) => {  return (<Item rounded={rounded} style={[styles.inputItem, style]}><Input         ref={ref}        autoFocus={true}        autoCapitalize="none"        placeholder={placeholderText}        keyboardType="default"        onChangeText={handleChange(fieldType)}        value={value}       /></Item>  );});

Codesandbox:https://snack.expo.io/@nhammad/carefree-cereal

Using theme for styling in react native with typescript

$
0
0

I can use theme variable in makeStyles function and also I want to use theme variable in createStyles function

export type NamedStyles<T> = { [P in keyof T]: ViewStyle | TextStyle | ImageStyle }export const makeStyles = <T extends NamedStyles<T> | NamedStyles<any>>(  styles: (theme: Theme) => T) =>  <T extends NamedStyles<T> | NamedStyles<any>>() => {  const currentTheme = useTheme();  return styles(currentTheme);};const baseStyles = makeStyles((theme:Theme) => ({     // I can use here     container:{backgroundColor:theme.colors.primary}}))export const createStyles = <T extends NamedStyles<T> | NamedStyles<any>>(overrides : T | NamedStyles<T>) => {    return create({...baseStyles, ...overrides})  }//in component.tsx    const styles = createStyles({        // I want to use here as well    })

React Native: I want the app to navigate to "Home" after someone signed in

$
0
0

I want my app to navigate home after someone signed in, but it don't work it is because the roots didn't update. You can see here the App code to understand what I want to say.

Which is the best way to handle this in React Native?

  • to give up the ternary operator

  • to refresh the page after someone logged in(I saw that the manual refresh push to home, but I don't know how to force refresh with navigation)

React-Native custom Text component with Typescript : "Conversion of type React.ReactNode to type Text..."

$
0
0

I've been trying to implement the following custom Text component in React Native.

import React from 'react';import { Text as RNText, TextStyle } from 'react-native';export interface TextProps {  children: React.ReactNode;   type?: 'title' | 'large' | 'medium' | 'small';  weight?: 'thin' | 'light' | 'regular' | 'bold';  color?: string;  style?: TextStyle;};const Text = ({  children,  type,  weight,  color,  style = {}}: TextProps) => {  const fontSize = () => {    switch (type) {      case 'title':        return 24;      case 'large':        return 28;      case 'medium':        return 18;      case 'small':        return 14;      default:        return 16;    }  };  const fontFamily = () => {    switch (weight) {      case 'thin':        return 'Lato-Thin';      case 'light':        return 'Lato-Light';      case 'regular':        return 'Lato-Regular';      case 'bold':        return 'Lato-Bold';      default:        return 'Lato-Regular';    }  };  return (<RNText       style={{        fontFamily,         fontWeight,         color: color || '#fff',         {...style}      }}>      {children}</RNText>  );};export default Text;

However, I have an error on <RNText> : "Type {} is missing the following properties from type 'Text': measure, measureInWindow, measureLayout, setNativeProps and 9 more"

If i remove the style props of the <RNText> component, I've got another error in VSCode: "Conversion of type {children: React.ReactNode} to type Text may be a mistake because neither type sufficiently overlaps with the other. If it was intentional, convert the expression to unknown first"

Seems like I would have the set the wrong type for the children props ?

Thanks in advance !


pass a function to a custom react hook

$
0
0

Previously, I was using a graphql query like this. The data is returned from the query and I use setShowFlatListwith the datareturned:

  const [loadUsers, { data }] = useUsersLazyQuery({    onCompleted: () => {      setShowFlatList(data);    },});

Now I am creating a custom react hook where I use this graphql query. It looks like this:

export const useLoadUsers = (onCompleted: any) => {  const [usersQuery, { data }] = useUsersLazyQuery({    onCompleted: () => {      if(onCompleted){        onCompleted();      }    },    onError: onLoadUserError,    fetchPolicy: 'network-only',  });const loadUsers = async (phoneNumber: number,) => {  const data = await usersQuery({    variables: {      where: {        OR: [          { phoneNumber: newPhoneNumber }        ],      },    },    });  return data;};return loadUsers;};

But I cannot figure out how to pass the setShowFlatList function to the onCompleted of the hook, such that I can still use dataas its parameter from within the hook.

tsdoc-param-tag-with-invalid-name: The @param block should be followed by a valid parameter name (TypeScript ESLint and React)

$
0
0

I'm using JSDoc and TSDoc for a React Native project with TypeScript. There is some strange behavior when documentings props.

All @param: props.propName are underlined with message:

tsdoc-param-tag-with-invalid-name: The @param block should be followed by a valid parameter name: The identifier cannot non-word characterseslinttsdoc/syntax

Also, I'm obliged to add : Props twice because if I only put it in FC the props are underlined with:

'onPress' is missing in props validationeslintreact/prop-types

The code:

import React, { useContext, FC } from 'react'import { GestureResponderEvent, ViewStyle } from 'react-native'import { useNavigation } from '@react-navigation/native'import { UserAvatarContext } from '../apps'import Avatar from './Avatar'interface Props {  size?: number  radius?: number  style?: ViewStyle  onPress?: (event: GestureResponderEvent) => void}/** * Display the user profile avatar and link * * @param props - React props * @param props.size - the size of the avatar in pixels * @param props.radius - the border radius in pixels * @param props.onPress - the function to use when pressing the avatar (by default, navigate to the user profile page) * @param props.style - Additional style information * @returns The avatar icon */const UserAvatar: FC<Props> = ({ size = 40, radius, style, onPress }: Props) => {  const navigation = useNavigation()  const { source } = useContext(UserAvatarContext)  const defaultOnPress = (): void => navigation.navigate('My profile')  return <Avatar source={source} onPress={onPress || defaultOnPress} size={size} style={style} radius={radius} />}export default UserAvatar

I'd like it to be clean, yet I feel I need to make some configurations or modify the way of declaring my props. Any idea?

Thanks

Check an Image URL is valid

$
0
0

My goal is to check an image source url to check whether it is valid or not. If it is valid, display the React Native Image as normal and if not, replace it with a local placeholder image. However, the following typescript function never seems to return anything and nothing is displayed.

renderImage(): JSX.Element {    fetch(this.props.imageUrl)    .then(res => {      if(res.status == 404) {        return (<Image            source={require('../images/nasa-logo.png')}            style={styles.imageThumbnail}          />        )      } else {        return (<Image            source={{uri: this.props.imageUrl}}            style={styles.imageThumbnail}          />        )      }    })    .catch(err => {      return (<Image          source={require('../images/nasa-logo.png')}          style={styles.imageThumbnail}        />      )    })    return null // <-- skips to here  }

Extends Console Interface for TypeScript

$
0
0

I would like to add an object in the window.console global.

import Reactotron from 'reactotron-react-native';window.console.tron = Reactotron;

Although when I do that, TypeScript complains about the new object:

error TS2339: Property 'tron' does not exist on type 'Console'.

I was thinking to extends the Console interface:

interface ConsoleWithTron extends Console {  tron: any};

Although, I'm not sure how to assign this new interface to my global console object?

Help would be great!

Thanks.

Keep getting error: $.deferred is not a function

$
0
0

I've installed jquery and @types/jquery. I want to use jquery.Deferred() but when i try to use it I get error that "$.Deferred is not a function".

import * as $ from "jquery";u// somewhere in codelet dfd = $.Deferred<      { response: JQueryXHR; body?: any },      { response: JQueryXHR; errorThrown: string }>();

It is from code that was generated by https://github.com/OpenAPITools/openapi-generator for typescript. I'm using it in React Native app. Any suggestions?Thanks!

The props not changing the background button color

$
0
0

Objective

I am trying to switch the background color button if the off props are passed. Something like, if the button contains de off, the background color button will red and if not contains, the background color will green.

What happening?

I am passing the props but the color not change and the two buttons that I have stay green.

Code

Home

<ContainerRow><Button onPress={handleConnectBluetooth}>Conectar</Button><Button onPress={handleDesconnectBluetooth} off={false}>        Desconectar</Button></ContainerRow>

Here the button with the text Desconectar needs to be red.

Button component

import React from 'react';import {RectButtonProperties} from 'react-native-gesture-handler';import {Container, ButtonText} from './styles';interface ButtonProps extends RectButtonProperties {  children: string;  off?: boolean;}const Button: React.FC<ButtonProps> = ({children, off, ...rest}) => (<Container off {...rest}><ButtonText>{children}</ButtonText></Container>);export default Button;

Here the props off inside the parameters, say off is defined but never used.

Button style

import styled from 'styled-components/native';import {RectButton} from 'react-native-gesture-handler';interface IButtonProps {  off: boolean;}export const Container = styled(RectButton)<IButtonProps>`  height: 40px;  background: ${(props) => (props.off ? '#29ed1f' : '#ff0000')};  border-radius: 10px;  margin-top: 8px;  justify-content: center;  align-items: center;`;export const ButtonText = styled.Text`  color: #312e38;  font-size: 18px;`;

Passing in a Function with Parameters into a Child Component in React Native Typescript

$
0
0

I'm trying to pass the following function into a child component as a prop, along with a string parameter:

navigateToDetailsPage(nasaId: string) {  this.props.navigation.navigate('Details', {     nasaId: nasaId  })}

I pass in the function & parameter into the child component like so:

<NasaImage  onPress={this.navigateToDetailsPage(result.data[0].nasa_id)}  .../>

In the child component NasaImage I have declared onPress as:

onPress: () => void

However, I am getting the following error in the parent component:

Type 'void' is not assignable to type '() => void'.ts(2322)NasaImage.tsx(12, 3): The expected type comes from property 'onPress'


React Native Vscode TypeScript debugger stepping extremely slow

$
0
0

I've got a few projects that use TypeScript (some with React, some with React Native), but for some reason, a particular React Native project started to get extremely slow while debugging. Here's an actual step over recording (I've reduced frame rate of GIF, but it's the same time that it takes to wait until stepping to next line):

enter image description here

The project doesn't have anything super large or fancy, and Vscode is perfectly okay with debugging TypeScript blazingly fast on my other projects. It used to debug this one just as fast too. I haven't worked on this project for a few weeks, meanwhile updated many dependencies, Vscode, even macOS itself, coded for a while without debugging, and only now I realized it got slower at some point, but I have no idea where.

What might be going on?(TypeScript 3.8.3, React Native 0.62.2, React 16.12.0, Vscode 1.43.2, macOS 10.15.4)

setState with a value from a different file

$
0
0

On my screen file, I run a graphql query and fetch data. I use setShowFlatListwith the data returned:

  const [showFlatList, setShowFlatList] = useState('');  ....  const [loadUsers, { data }] = useUsersLazyQuery({    onCompleted: () => {      setShowFlatList(data);    },});

Now, I am creating a custom react hook that I can call when I want to run the query. It looks like this:

export const useLoadUsers = (onCompleted: any) => {  const [usersQuery, { data }] = useUsersLazyQuery({    onCompleted: () => {      if(onCompleted){        onCompleted(data);        //[usersQuery, { data }]      }    },    onError: onLoadUserError,    fetchPolicy: 'network-only',  });const loadUsers = async (phoneNumber: number,) => {  const data = await usersQuery({    variables: {      where: {        OR: [          { phoneNumber: newPhoneNumber }        ],      },    },    });  return data;};return loadUsers;};

If I pass lets say setShowFlatList('true')then it would work. However, I want to setShowFlatList(data) and I don't know how to make that work since the data is obtained within the hook itself.

From my screen file,I cannot pass setShowFlatList(data) since data isn't defined there. Similarly, I can't just pass setShowFlatList alone either. So, how can I do setShowFlatList(data) within the hook then?

Navigation Structure on React Native Typescript for Duplicate Page

$
0
0

I have the following navigation structure in my app.tsx file:

const HomeStack = createStackNavigator<HomeStackParamList>()function HomeStackScreen() {  return (<HomeStack.Navigator><HomeStack.Screen        name='Home'        component={NasaImageList}        options={{ title: 'NASA Image Search' }}      /><HomeStack.Screen        name='Details'        component={NasaImageDetails}        options={({ route }) => ({ title: route.params.title })}      /></HomeStack.Navigator>  )}const FavouriteStack = createStackNavigator<FavouriteStackParamList>()function FavouriteStackScreen() {  return (<FavouriteStack.Navigator><FavouriteStack.Screen        name="Favourites"        component={NasaImageFavouriteList} /><FavouriteStack.Screen        name="Details"        component={NasaImageDetails}        options={({ route }) => ({ title: route.params.title })}} /></FavouriteStack.Navigator>  )}const Tab = createBottomTabNavigator()export default class App extends Component {  render() {    return (<NavigationContainer><Tab.Navigator><Tab.Screen            name="Home"            component={HomeStackScreen}          /><Tab.Screen            name="Favourites"            component={FavouriteStackScreen} /></Tab.Navigator></NavigationContainer>    )  }

The route parameters are defined in the HomeStackParamList and FavouriteStackParamList types as declared below. These are the same at the moment but they are likely to change hence the need to keep them separate.

export type HomeStackParamList = {  Home: undefined  Details: {    nasaId: string    title: string  }}export type FavouriteStackParamList = {  Favourites: undefined  Details: {    nasaId: string    title: string  }}

The navigation prop type being passed into my NasaImageDetails component that forms the screen component 'Details' is defined as below:

export type NasaImageDetailsHomeNavigationProp = StackNavigationProp<HomeStackParamList,'Details'>export type NasaImageDetailsFavouriteNavigationProp = StackNavigationProp<FavouriteStackParamList,'Details'>

I end up with two navigation prop types from the two parameter lists which is not ideal. What are the best practises for this situation in react native typescript?

Using forwardRef with typescript and react native

$
0
0

I have Onboarding and Slider components. I want to pass prop scrollview's ref to slider component and using it in button to get next slider on screen

     const Onboarding = () => {  const { width } = useOrientation();  const [currentIndex, setCurrentIndex] = useState<number>(0);  const scroll = useRef<Animated.ScrollView>(null);  const onScroll = ({ nativeEvent }: any) => {    // the current offset, {x: number, y: number}    // page index    const index = Math.round(nativeEvent.contentOffset.x / width);    setCurrentIndex(index);  };  return (<Box flex={1}><Animated.ScrollView ref={scroll} onScroll={onScroll} horizontal>        {slides.map((data, index) => (<Slide            key={index}            data={data}            ref={scroll}            {...{ currentIndex, index }}          />        ))}</Animated.ScrollView></Box>  );};interface SlideProps {  data: {    label: string;    description: string;    src: string;  };  currentIndex: number;  index: number;}export const Slide = forwardRef<Animated.ScrollView, SlideProps>(  ({ data, currentIndex, index }: SlideProps, ref) => {    const { width, height } = Dimensions.get("window");    const aspect = height / width;    return (      //error here<TouchableOpacity onPress={() => ref?.current?.getNode().scrollTo(width*(index+1))}> </TouchableOpacity>)

Error :Property 'current' does not exist on type '((instance: ScrollView | null) => void) | MutableRefObject<ScrollView | null>'.Property 'current' does not exist on type '(instance: ScrollView | null) => void

The device.servicesUUIDs out the then.catch print but inside the value is null

$
0
0

I am using the library react-native-ble-plx to connect Bluetooth using my application, but I need some values, when I log console.log(device) returns me any values, and I found the servicesUUIDs, it is an array an the position zero, contains the id about the module chip I am using, but when I print inside the then().catch(), does not log the value that I need, but the out the then().catch(), print the ID.

Function scanAndConnect()

async function scanAndConnect() {    manager.startDeviceScan(null, null, async (error, device) => {      if (error) {        console.log('Error at if(error): ', error);        return null;      }      if (!device) {        console.log('Error at if(device === null)');        return null;      }      if (device.name === 'MLT-BT05') {        // manager.stopDeviceScan();        /* serviceUUID = 0000ffe0-0000-1000-8000-00805f9b34fb */        if (device.serviceUUIDs) {          console.log(device.serviceUUIDs);        }        // Proceed with connection.        device          .connect()          .then(async (d) => {            const servicesAndCharacteristics = await d.discoverAllServicesAndCharacteristics();            return servicesAndCharacteristics;          })          .then((d) => {            console.log('d.id: ', d.id);            console.log('d.name: ', d.name);            if (d.serviceUUIDs) {              console.log('d.servicesUUIDs[0]: ', d.serviceUUIDs[0]);            }            if (d.solicitedServiceUUIDs) {              console.log('d.solicitedServiceUUIDS: ',                d.solicitedServiceUUIDs[0],              );            }          })          .catch((err) => {            console.log(err);          });      }    });  }
Viewing all 6214 articles
Browse latest View live


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