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

Type 'Color' is not assignable to type 'string'

$
0
0

I am using npm color package. I am completly new to typescript react-native. Here I am trying to use Color property on shadow color property something like this.

const BACKGROUND = "#88B04B";const Styles = StyleSheet.create({  topMorp: {    shadowOffset: {      width: -6,      height: -6,    },    shadowOpacity: 1,    shadowRadius: 6,    shadowColor: Color(BACKGROUND).lighten(0.5).alpha(0.5),  },

But here my code complains saying Type 'Color<ColorParam>' is not assignable to type 'string'. I don't know how to fix this any help would be great.


React-native flatlist is sharing props between components on isLoading

$
0
0

I'm currently making a list of items in react-native using flatlist, the issue i'm facing is that its sharing my isloading prop between all instances of the items in the list. meaning that if i click on one item all items then show that it is loading. I've tried extraData and unique keys but im really unsure of what to do.

interface IBugListProps {  onItemSelected: (bugListItem: BugModel) => void;  onDeletePress: (bugListItem: BugModel, index: number) => void;  refreshing: boolean;  onRefresh: () => any;  bugListItems: BugModel[];  isLoading: boolean;}const BugList = (props: IBugListProps) => {  return (<FlatList      data={props.bugListItems}      refreshControl={<RefreshControl          progressBackgroundColor={'#000000'}          colors={['#00DA8B']}          refreshing={props.refreshing}          onRefresh={props.onRefresh}        />      }      extraData={props}      keyExtractor={listItem => (listItem.id as number).toString()}      renderItem={({ item, index, separators }) => (<Fragment><SwipeableItem            index={index}            rightText={'Delete'}            onPressRight={() => props.onDeletePress(item, index)}            isLoading={props.isLoading}><BugListItem              key={item.id}              bugListItem={item}              onItemSelected={_item => props.onItemSelected(_item)}            /></SwipeableItem></Fragment>      )}    />  );}export default BugList;

The component that has the same props for all instances of this component

interface IListItemProps {    isLoading?: boolean;    index: number    leftText?: string;    onSwipeLeft?: () => void;    onPressLeft?: () => void;    rightText?: string;    onSwipeRight?: () => void    onPressRight?: () => void;    children: React.ReactElement<any>;}const SwipeableItem = (props: IListItemProps) => {    const isLeft: boolean = (props?.leftText !== undefined) || (props?.onSwipeLeft !== undefined) || (props?.onPressLeft !== undefined)    const isRight: boolean = (props?.rightText !== undefined) || (props?.onSwipeRight !== undefined) || (props?.onSwipeRight !== undefined)    console.log(props.index)    return (<Fragment >            {(isLeft && isRight) ? (<Swipeable                    renderLeftActions={(progress, dragX) => (<LeftActions isLoading={props?.isLoading!} progress={progress} dragX={dragX} onPress={props?.onPressLeft} text={props?.leftText!} />                    )}                    onSwipeableLeftOpen={props?.onSwipeLeft}                    renderRightActions={(progress, dragX) => (<RightActions isLoading={props?.isLoading!} progress={progress} dragX={dragX} onPress={props?.onPressRight} text={props?.rightText!} />                    )}                    onSwipeableRightOpen={props?.onSwipeRight}>                    {props.children}</Swipeable>            ) : (<Fragment>                        {isLeft && (<Swipeable                                renderLeftActions={(progress, dragX) => (<LeftActions isLoading={props?.isLoading!} progress={progress} dragX={dragX} onPress={props?.onPressLeft} text={props?.leftText!} />                                )}                                onSwipeableLeftOpen={props?.onSwipeLeft}>                                {props.children}</Swipeable>                        )}                        {isRight && (<Swipeable                                renderRightActions={(progress, dragX) => (<RightActions isLoading={props?.isLoading!} progress={progress} dragX={dragX} onPress={props?.onPressRight} text={props?.rightText!} />                                )}                                onSwipeableRightOpen={props?.onSwipeRight}>                                {props.children}</Swipeable>                        )}</Fragment>                )}</Fragment>    )};export default SwipeableItem;

native base with a line

$
0
0

I am using native base's item and want to style it such that it has a line. Currently, it's simply invisible. All I can see is the placeholder text and if I change the background color, then I can see that too. But there's no border/line. How can I fix this?

<Input style={styles.newFieldInput}                      onChangeText={handleChange('phoneNumber') as (text: string) => void}                      onBlur={handleBlur('phoneNumber') as (event: any) => void}                      value={values.phoneNumber}                      placeholder="49152901820"                    />
 newFieldInput: {    width: moderateScale(320),    backgroundColor: 'white',  },

I have tried passing in roundedor line as attributes but I get overloading errors as these attributes don't exist on < Input >

Also, is there any way I can add in icon into the beginning of the Input? Or will I necessarily have to wrap it in another component?

Type is missing the following properties from type in TypeScript of React-Native app

$
0
0

I have installed https://github.com/react-native-community/react-native-modal library and I need to make a wrapper Modal class. The first initialize Interface. It extends from a few interfaces from react-native and react-native-modal libraries. It means I can use all properties from both of them:

import { ModalProps } from 'react-native';import { ReactNativeModal, ModalProps as ModalRNProps } from 'react-native-modal';export interface IModalProps extends Omit<ModalProps, 'onShow'>, ModalRNProps {  showCloseButton?: boolean;  showDoneBar?: boolean;}export class ModalNew extends React.Component<IModalProps> {  public render() {    const {      style,      children,      showCloseButton,      showDoneBar,      animationType,      onRequestClose,      ...props    } = this.props;    return (<ReactNativeModal       isVisible={this.props.isVisible}       onModalWillHide={onRequestClose}       animationIn={'slideInUp'}       animationOut={'slideOutDown'}       animationOutTiming={600}       useNativeDriver={true}       backdropOpacity={0.6}       backdropColor={theme.black}       style={style}       {...props}>       {children}</ReactNativeModal>    );  }}

But after when I use it in other component:

import React, { Component } from 'react';import { ModalNew } from './ModalNew';export class FooterHiddenPanel extends Component {  const props = this.props;  render() {    return (<ModalNew isVisible={props.isActive} onRequestClose={props.onRequestClose}><Text>This is </Text></ModalNew>    );  }}

I get this error:

enter image description here

It means I have to use all properties from both PropsTypes that I has extended my interface. But I don't need all of them. If I extend my class from a few interfaces I must implement all properties? Can you tell me please how can I get rid from this error?

Unable to resolve module 'module://graphql/language/parser.js'

$
0
0

I am trying to make a React Native TypeScript project on Snack Expo. Although I have already added graphql in the package.json as well as the types file, I still get this error :

Device: (1:8434) Unable to resolve module 'module://graphql/language/parser.js'  Evaluating module://graphql/language/parser.js  Evaluating module://graphql-tag.js  Evaluating module://graphql/loadCountries.tsx.js  Evaluating module://App.tsx.js  Loading module://App.tsx

How can I fix this? I am not using an JS Files. Here's the link to the expo:

https://snack.expo.io/qYOFLsmjv

React Typescript: Add another row of fields to form with button

$
0
0

I'm building a product sales form that allows users to add a product name, quantity, and price. By default I want the form to show 3 rows and if they want to add another product, there would be a button that says "Add Product" which will then add another two of product name, quantity, and price.

I want to set the limit to allow to a max of 10 rows (10 products).

addProductRow(event) {     event.preventDefault();}<div className={`${styles.flexWrap} ${styles.flexRow}`}><div><label>            Product Name</label><input            value={this.state.DetailedDescription1}            onChange={this.handleChangeDetailedDescription1}            type="text"            className="phone validate"            name="Detailed Description"            maxLength={45}        /></div>  <div><label>            Quanitity</label><input            value={this.state.Quantity1}            onChange={this.handleChangeQuantity1}            type="number"            className="phone validate"            name="Quantity #1"            maxLength={9}            pattern='[0-9]{0,5}'        /></div><div><label>            Total</label><input            value={this.state.Total1}            onChange={this.handleChangeTotal1}            type="number"            className="phone validate"            name="Quantity #1"            maxLength={9}            pattern='[0-9]{0,5}'        /></div></div><button onClick={this.addProductRow}>Add New Product</button><button onClick={this.removeProductRow}>X</button>

So when the user clicks "Add New Product" a new row will show with the above fields labeled this.state.DetailedDescription2 and this.handleChangeDetailedDescription1 and so forth.

Why the goBack function doesn't work? React Native

$
0
0

I am new in React Native, I am working on an app where I had to add a prefabricated header, which brings a button to which I want to set the option to go back with the function goBack of Navigation, however the button does not Nothing, also I tried with Navigation.navigate ('route'), but the issue continues. I would really appreciate it if you can help with this.

The code:

import { NavigationContainer, useNavigationState} from '@react-navigation/native';import { NavigationActions } from 'react-navigation';import { createStackNavigator } from '@react-navigation/stack';import { Toolbar } from 'react-native-material-ui';import * as React from 'react';import { Platform, StatusBar, StyleSheet, View, Text } from 'react-native';import BottomTabNavigator from '../../navigation/BottomTabNavigator';import LinkingConfiguration from '../../navigation/LinkingConfiguration';import CatHome from '../../screens/subScreens/CatHome';const Stack = createStackNavigator();export default function Navigator({navigation}) {  const SearchBar= ()=>{    //const { navigate } = this.props.navigation;    return(<Toolbar        leftElement= {backOption()}        onLeftElementPress= {()=>navigation.goBack()}        //isSearchActive= {true}        style={{          container: styles.searchBar,        }}        centerElement="DIRECTAPP"        searchable={{          autoFocus: true,          placeholder: 'Buscar',        }}        rightElement={{            menu: {                icon: "more-vert",                iconProps : {                  size: 30,                  color: 'gray',                },                labels: ["Locación", "Contáctanos"]            }                }}        onRightElementPress={ (label) => { console.log(label) }}      />    );  }  return (<View style={styles.container}>      {Platform.OS === 'ios'&& <StatusBar barStyle="dark-content" />}<NavigationContainer linking={LinkingConfiguration}><Stack.Navigator screenOptions={{          headerLeft: null,          headerTitle: props => <SearchBar {...props} />,          headerStyle: {            backgroundColor: '#9acd32',          }        }}><Stack.Screen name="Root" component={BottomTabNavigator} /><Stack.Screen name="CatHome" component={CatHome} /></Stack.Navigator></NavigationContainer></View>  );}function backOption (){  //const Route=useRoute();  const state = useNavigationState(state => state);  const routeName = (state.routeNames[state.index]);  //console.log(routeName);  if (routeName=='Root') {    return ''  }  else {    return 'arrow-back'  };}const styles = StyleSheet.create({    container: {      flex: 1,      backgroundColor: '#fff',    },    searchBar: {      backgroundColor: '#9acd32',      width: '100%',      shadowOffset:  { width: 1, height: 13},      shadowOpacity: 0.1,    }  });

Unable to resolve "./SafeAreaContext"

$
0
0

I recently set up react-native project with expo and later on I added @react-navigation packages.

It seems like this wasn't enough as NavigationContainer render complains about SafeAreaContext

I tried to install required packages with expo install react-native-safe-area-context ... but It didn't solve it.

Thought deleting node_modules&& npm install could help, but it didn't work either.

There were related questions to this issue, but they didn't provide much help

I will appreciate your help.

Here's what I get in android emulator

red screen of death by react=native

terminal

Unable to resolve "./SafeAreaContext" from "node_modules\react-native-safe-area-context\src\index.tsx"Failed building JavaScript bundle.

App.tsx

import React, { useState } from 'react';import { AppLoading } from 'expo'import { View, Text } from 'react-native';import { NavigationContainer } from '@react-navigation/native';import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';import { createStackNavigator } from '@react-navigation/stack';function Test() {  return (<View      style={{ flex: 1, justifyContent: 'space-between', alignItems: 'center' }}><Text>Test</Text></View>  );}const Stack = createStackNavigator();const Tab = createBottomTabNavigator();export default function App() { const [loaded, setLoaded] = useState(false);  if(!loaded) {    return <AppLoading      startAsync={() => Promise.resolve()}      onFinish={() => setLoaded(true)}/>  }  return <NavigationContainer></NavigationContainer>}

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": {"@expo/vector-icons": "^10.2.0","@react-native-community/masked-view": "^0.1.6","@react-navigation/bottom-tabs": "^5.5.1","@react-navigation/native": "^5.5.0","@react-navigation/stack": "^5.4.1","expo": "^37.0.12","expo-asset": "^8.1.5","expo-constants": "^9.0.0","expo-linking": "^1.0.1","expo-splash-screen": "^0.2.3","expo-web-browser": "^8.2.1","react": "~16.9.0","react-dom": "~16.9.0","react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz","react-native-gesture-handler": "~1.6.0","react-native-reanimated": "~1.7.0","react-native-safe-area-context": "0.7.3","react-native-safe-area-view": "^1.1.1","react-native-screens": "~2.2.0","react-native-web": "~0.11.7","react-redux": "^7.2.0","redux": "^4.0.5"  },"devDependencies": {"@babel/core": "^7.8.6","@types/react": "~16.9.23","@types/react-native": "~0.61.17","babel-preset-expo": "~8.1.0","typescript": "~3.8.3"  },"private": true}

Unhandled JS Exception: Requiring unknown module "9"

$
0
0

So I'm trying to set up the navigation for a log in screen and I've tried relinking dependecies and installing packages all over again and I've only worked on two files. I am working on MacOS and simulating on iOS 13.5.

This is the complete error when trying to simulate.

App.js

import React, { Component } from 'react'import {  StyleSheet,  View} from 'react-native'import Mystack from './navigators/StackNavigator'export default class App extends Component {render() {  return (<NavigationContainer><Mystack/></NavigationContainer> ) }} const styles = StyleSheet.create({  container: {}, })

and StackNavigator.js

import * as React from 'react';import { createStackNavigator} from '@react-navigation/stack';import { NavigationContainer } from '@react-navigation/native';import LogIn from './src/components/LogIn.js'import SignUp from './src/components/SignUp.js'import Dashboard from './src/components/Dashboard.js'const Stack = createStackNavigator();function Mystack() {     return(<Stack.Navigator initialRouteName = "LogIn"         screenOptions = {{         headerTitleAlign: 'center',         HeaderStyle: {             backgroundColor: "#FFF700",         },           headerTintColor: '#FFF',           headerTitleStyle: {               fontWeight: 'bold',         },        }}><Stack.Screen name = "LogIn"        component = {LogIn}        options = {{           title: 'LogIn',           headerShown: false        }}/><Stack.Screen name = "SignUp"         component = {SignUp}         options = {{             title: 'SignUp',             headerShown: false        }}/><Stack.Screen name = "Dashboard"        component = {Dashboard}        options = {{            title: 'Dashboard'        }        }/></Stack.Navigator>       )       }      export default Mystack;

TS compatibility for libraries with out @types

$
0
0

I am currently trying to install and integrate react-native-credit-card-input on to a typescript project.

When I run run npm install @types/react-native-credit-card-input --saveand getting the following

npm ERR! code E404npm ERR! 404 Not Found - GET https://registry.npmjs.org/@types%2freact-native-credit-card-input - Not foundnpm ERR! 404npm ERR! 404  '@types/react-native-credit-card-input@latest' is not in the npm registry.npm ERR! 404 You should bug the author to publish it (or use the name yourself!)npm ERR! 404npm ERR! 404 Note that you can also install from anpm ERR! 404 tarball, folder, http url, or git url.

My question is if the @types lib does not exist for a specific library, does that mean there is no way to integrate that library on the a typescript project?

Thanks!

too many rerenders on using useState

$
0
0

I am calling the contactsfunction from the main return. I don't see any error until here:

 const showContacts = React.useCallback(    (data: UsersQueryHookResult) => {      if (data) {        return (<View style={styles.users}></View>        );      }    },    [userData],  );  const contacts = () => {    console.log('running');    const { loading, error, data } = useUsersQuery({      variables: {        where: { id: 34 },      },    });    console.log('DATA COMING', data);    //setUserData(data);    //console.log('contact name', data.users.nodes[0].userRelations[0].relatedUser.firstName);  };  return (<SafeAreaView style={{ flex: 1 }}><Container style={{ flex: 1, alignItems: 'center' }}><Item style={styles.addToWhitelist}><Icon            name="add"            onPress={() => navigation.navigate('AddContactTry')}          /><Text style={styles.addToContactTitle}>Add contact</Text></Item><Text onPress={() => navigation.navigate('Home')}>Zurück</Text><View style={{ width: moderateScale(350) }}><Text>Keine Kontacte</Text></View>        {contacts()}</Container></SafeAreaView>  );};

Now I want to do some conditional rendering on the basis of the results from contacts. However, as soon as I uncomment setUserData(data); I get an error that too many re-renders. I don't get what I am doing wrong in showUsersto get this error.

Edit:

I tried this but it gives an invalid hook call error:

export const Whitelist: React.FunctionComponent = (props) => {  const [userData, setUserData] = useState<UsersQueryHookResult>(''); useEffect(() => {    // Your function to fetch/get contacts    const data = contacts();    setUserData(data);  }, [])  const showContacts = React.useCallback(    (data: UsersQueryHookResult) => {      if (data) {        return (<View style={styles.users}></View>        );      }    },    [userData],  );  const contacts = () => {    console.log('running');    const { loading, error, data } = useUsersQuery({      variables: {        where: { id: 34 },      },    });    console.log('DATA COMING', data);    //setUserData(data);  };  return (<SafeAreaView style={{ flex: 1 }}><Container style={{ flex: 1, alignItems: 'center' }}><Item style={styles.addToWhitelist}><Icon            name="add"            onPress={() => navigation.navigate('AddContactTry')}          /><Text style={styles.addToContactTitle}>Add contact</Text></Item><Text onPress={() => navigation.navigate('Home')}>Zurück</Text>        {/* {contacts()} */}</Container></SafeAreaView>  );};

reset conditional rendering from separate component

$
0
0

Previously I was using the function showUsers and {isSubmitted && showUsers(userData)} to conditionally render some items after a graphql query. In this case, I was using

setIsSubmitted(false);setUserData(null);

on the button to reset data and stop the conditional rendering. However, now I have moved showUsersto Users a separate component. In this case, I cannot figure out a way to pass setIsSubmittedand setUserData. I want to fix it such that after a mutation runs, the rendering should disappear.

The commented out parts are what I was using earlier.

export const AddContactTry: React.FunctionComponent = () => {  const validationSchema = phoneNumberValidationSchema;  const { values, handleChange, handleSubmit, dirty, handleBlur, isValid, resetForm, isSubmitting, setSubmitting, touched}= useFormik({    initialValues: {      phoneNumber: '',    },    //isInitialValid:false,    validationSchema,    onSubmit: (values: FormValues) => {      handleSubmitForm(values);    },  });  console.log('isDirty', dirty);  console.log('isValid', isValid);  console.log('phone numm', values.phoneNumber);  console.log('submitting status', isSubmitting);  const [isSubmitted, setIsSubmitted] = useState(false);  const [userData, setUserData] = useState<UsersLazyQueryHookResult>('');  const navigation = useNavigation();  const _onLoadUserError = React.useCallback((error: ApolloError) => {    Alert.alert('Oops, try again later');  }, []);  // const [  //   createUserRelationMutation,  //   {  //     data: addingContactData,  //     loading: addingContactLoading,  //     error: addingContactError,  //     called: isMutationCalled,  //   },  // ] = useCreateUserRelationMutation({  //   onCompleted: () => {  //     Alert.alert('Contact Added');  //   },  // });  // const showUsers = React.useCallback(  //   (data: UsersLazyQueryHookResult) => {  //     if (data) {  //       return (  //         <View style={styles.users}>  //           {data.users.nodes.map(  //             (item: { firstName: string; lastName: string; id: number }) => {  //               const userName = item.firstName  //                 .concat('')  //                 .concat(item.lastName);  //               return (  //                 <View style={styles.item} key={item.id}>  //                   <Thumbnail  //                     style={styles.thumbnail}  //                     source={{  //                       uri:  //                         'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',  //                     }}></Thumbnail>  //                   <Text style={styles.userName}>{userName}</Text>  //                   <View style={styles.addButtonContainer}>  //                     <Button  //                       rounded  //                       style={styles.addButton}  //                       onPress={() => {  //                         //addContact(Number(item.id));  //                         setIsSubmitted(false);  //                         setUserData(null);  //                       }}>  //                       <Icon  //                         name="plus"  //                         size={moderateScale(20)}  //                         color="black"  //                       />  //                     </Button>  //                   </View>  //                 </View>  //               );  //             },  //           )}  //         </View>  //       );  //     }  //   },  //   [createUserRelationMutation, userData],  // );  // const addContact = React.useCallback(  //   (id: Number) => {  //     console.log('Whats the Id', id);  //     createUserRelationMutation({  //       variables: {  //         input: { relatedUserId: id, type: RelationType.Contact, userId: 30 },  //       },  //     });  //   },  //   [createUserRelationMutation],  // );  const getContactId = React.useCallback(    (data: UsersLazyQueryHookResult) => {      //resetForm();      if (data) {        if (data.users.nodes.length == 0) {          Alert.alert('No User Found');        } else {          setUserData(data);        }      }    },    //[addContact],    [],  );  const [loadUsers] = useUsersLazyQuery({    onCompleted: getContactId,    onError: _onLoadUserError,  });  const handleSubmitForm = React.useCallback(    (values: FormValues) => {      setIsSubmitted(true);      const plusSign = '+';      const newPhoneNumber = plusSign.concat(values.phoneNumber);      console.log('Submitted');      loadUsers({        variables: {          where: { phoneNumber: newPhoneNumber },        },      });      resetForm();    },    [loadUsers],  );  // if (!addingContactLoading && isMutationCalled) {  //   if (addingContactError) {  //     Alert.alert('Unable to Add Contact');  //   }  // }  return (<SafeAreaView><View style={styles.container}><View style={styles.searchTopContainer}><View><View style={styles.searchFieldContainer}><View style={styles.form}><Item underline style={styles.newFieldInput} ><Icon name="mobile" color="black" size={26}></Icon><Input                       onChangeText={handleChange('phoneNumber') as (text: string) => void}                      onBlur={handleBlur('phoneNumber') as (event: any) => void}                      value={values.phoneNumber}                      placeholder="49152901820"                    /></Item></View><View style={styles.buttonContainer}><Button                  block                  danger                  bordered                  style={styles.button}                  // onPress={() => navigation.goBack()}                  //disabled={!isValid || !dirty}                  //disabled={isSubmitting}                  onPress={resetForm}                  ><Text>Abbrechen</Text></Button><Button                  block                  success                  // disabled={!isValid || !dirty}                  onPress={handleSubmit}                  style={styles.button}><Text>Speichern</Text></Button></View></View></View>          {/* {isSubmitted && showUsers(userData)} */}<User data={userData}></User></View></View></SafeAreaView>  );};
export const User: React.FunctionComponent<UserProps> = ({  data,  //isSubmitted,}) => {  console.log('user called');  const [    createUserRelationMutation,    {      data: addingContactData,      loading: addingContactLoading,      error: addingContactError,      called: isMutationCalled,    },  ] = useCreateUserRelationMutation({    onCompleted: () => {      Alert.alert('Contact Added');    },  });  const addContact = React.useCallback(    (id: Number) => {      console.log('Whats the Id', id);      createUserRelationMutation({        variables: {          input: { relatedUserId: id, type: RelationType.Contact, userId: 1 },        },      });    },    [createUserRelationMutation],  );  if (!addingContactLoading && isMutationCalled) {    if (addingContactError) {      Alert.alert('Unable to Add Contact');    }  }  if (!data) return null;  return (<View style={styles.users}>      {data.users.nodes.map(        (item: { firstName: string; lastName: string; id: number }) => {          const userName = item.firstName.concat('').concat(item.lastName);          return (<View style={styles.item} key={item.id}><Thumbnail                style={styles.thumbnail}                source={{                  uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',                }}></Thumbnail><Text style={styles.userName}>{userName}</Text><View style={styles.addButtonContainer}><Button                  rounded                  style={styles.addButton}                  onPress={() => {                    addContact(Number(item.id));                    //setIsSubmitted(false);                    //setUserData(null);                  }}><Icon name="plus" size={moderateScale(20)} color="black" /></Button></View></View>          );        },      )}</View>  );};

Currently, if the mutation is successful, I see the alert but the rendered items are still there.

inner return not rendering anything

$
0
0

Depending on what the results of the graphql query are, I am rendering some items in the function contact

export const Whitelist: React.FunctionComponent = (props) => {  const [userData, setUserData] = useState<UsersQueryHookResult>('');  const called = () => {    console.log('inner return')  }  const contacts = () => {    console.log('running');    const { loading, error, data } = useUsersQuery({      variables: {        where: { id: 34 },      },    });    console.log('DATA COMING', data);    return (<View style={styles.allUsers}>        {data.users.nodes.map(          (item: { firstName: string; lastName: string; id: number }) => {            const userName = item.firstName              .concat('')              .concat(item.lastName);            return (           <View style={styles.item} key={item.id}>                  {called()}  <Thumbnail                  style={styles.thumbnail}                  source={{                    uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',                  }}></Thumbnail><Text style={styles.userName}>{userName}</Text><View style={styles.addButtonContainer}><Button                    rounded                    style={styles.addButton}><Icon                      name="plus"                      size={moderateScale(20)}                      color="black"                    /></Button></View></View>            );          },        )}</View>    );  };  return (<SafeAreaView style={{ flex: 1 }}><Container style={{ flex: 1, alignItems: 'center' }}><Item style={styles.addToWhitelist}><Icon            name="add"            onPress={() => navigation.navigate('AddContactTry')}          /><Text style={styles.addToContactTitle}>Add contact</Text></Item><Text onPress={() => navigation.navigate('Home')}>Zurück</Text>        {contacts()}</Container></SafeAreaView>  );};

However, I don't see any items rendered. If I render something after the first return in contacts(for example a thumbnail), I am able to see that. However, I don't see anything from the second return. How can I fix this?

I tried to use {called()} in the inner return to debug. It should show a log but it doesn't.

Move Conditional Rendering to a Separate Component

$
0
0

In my code, I take an input from the user, run a graphql query and then conditionally render some items according to the results (via showUsers functions). However, instead of using showUsers here as a function, I want to make it a separate component where I can pass userData.

export const AddContactTry: React.FunctionComponent = () => {  const validationSchema = phoneNumberValidationSchema;  const { values, handleChange, handleSubmit, dirty, handleBlur, isValid, resetForm, isSubmitting, setSubmitting, touched}= useFormik({    initialValues: {      phoneNumber: '',    },    validationSchema,    onSubmit: (values: FormValues) => {      handleSubmitForm(values);    },  });  const [isSubmitted, setIsSubmitted] = useState(false);  const [userData, setUserData] = useState<UsersLazyQueryHookResult>('');  const navigation = useNavigation();  //const validationSchema = phoneNumberValidationSchema;  const [    createUserRelationMutation,    {      data: addingContactData,      loading: addingContactLoading,      error: addingContactError,      called: isMutationCalled,    },  ] = useCreateUserRelationMutation({    onCompleted: () => {      Alert.alert('Contact Added');    },  });  const showUsers = React.useCallback(    (data: UsersLazyQueryHookResult) => {      if (data) {        return (<View style={styles.users}>            {data.users.nodes.map(              (item: { firstName: string; lastName: string; id: number }) => {                const userName = item.firstName                  .concat('')                  .concat(item.lastName);                return (<View style={styles.item} key={item.id}><Thumbnail                      style={styles.thumbnail}                      source={{                        uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',                      }}></Thumbnail><Text style={styles.userName}>{userName}</Text><View style={styles.addButtonContainer}><Button                        rounded                        style={styles.addButton}                        onPress={() => {                          addContact(Number(item.id));                          setIsSubmitted(false);                          setUserData(null);                        }}><Icon                          name="plus"                          size={moderateScale(20)}                          color="black"                        /></Button></View></View>                );              },            )}</View>        );      }    },    [createUserRelationMutation, userData],  );  const addContact = React.useCallback(    (id: Number) => {      console.log('Whats the Id', id);      createUserRelationMutation({        variables: {          input: { relatedUserId: id, type: RelationType.Contact, userId: 30 },        },      });    },    [createUserRelationMutation],  );  const getContactId = React.useCallback(    (data: UsersLazyQueryHookResult) => {      //resetForm();      if (data) {        if (data.users.nodes.length == 0) {          Alert.alert('No User Found');        } else {          setUserData(data);        }      }    },    [addContact],  );  const [loadUsers] = useUsersLazyQuery({    onCompleted: getContactId,    onError: _onLoadUserError,  });  const handleSubmitForm = React.useCallback(    (values: FormValues) => {      setIsSubmitted(true);      const plusSign = '+';      const newPhoneNumber = plusSign.concat(values.phoneNumber);      console.log('Submitted');      loadUsers({        variables: {          where: { phoneNumber: newPhoneNumber },        },      });      resetForm();    },    [loadUsers],  );  return (<SafeAreaView><View style={styles.container}><View style={styles.searchTopContainer}><View><View style={styles.searchFieldContainer}><View style={styles.form}><Item underline style={styles.newFieldInput} ><Icon name="mobile" color="black" size={26}></Icon><Input                       onChangeText={handleChange('phoneNumber') as (text: string) => void}                      onBlur={handleBlur('phoneNumber') as (event: any) => void}                      value={values.phoneNumber}                      placeholder="49152901820"                    /></Item></View><View style={styles.buttonContainer}><Button                  block                  success                  disabled={!isValid || !dirty}                  onPress={handleSubmit}                  style={styles.button}><Text>Speichern</Text></Button></View></View></View>          {isSubmitted && showUsers(userData)}</View></View>      {/* <User data={userData}></User> */}</SafeAreaView>  );};

Currently, the rendering happens here:

 {isSubmitted && showUsers(userData)}

Now, to move the rendering to a separate component, I tried to do this. Currently, this works:

export const AddContactTry: React.FunctionComponent = () => {  const validationSchema = phoneNumberValidationSchema;  const { values, handleChange, handleSubmit, dirty, handleBlur, isValid, resetForm, isSubmitting, setSubmitting, touched}= useFormik({    initialValues: {      phoneNumber: '',    },    validationSchema,    onSubmit: (values: FormValues) => {      handleSubmitForm(values);    },  });  const [isSubmitted, setIsSubmitted] = useState(false);  const [userData, setUserData] = useState<UsersLazyQueryHookResult>('');  const navigation = useNavigation();  const _onLoadUserError = React.useCallback((error: ApolloError) => {    Alert.alert('Oops, try again later');  }, []);  // const [  //   createUserRelationMutation,  //   {  //     data: addingContactData,  //     loading: addingContactLoading,  //     error: addingContactError,  //     called: isMutationCalled,  //   },  // ] = useCreateUserRelationMutation({  //   onCompleted: () => {  //     Alert.alert('Contact Added');  //   },  // });  // const showUsers = React.useCallback(  //   (data: UsersLazyQueryHookResult) => {  //     if (data) {  //       return (  //         <View style={styles.users}>  //           {data.users.nodes.map(  //             (item: { firstName: string; lastName: string; id: number }) => {  //               const userName = item.firstName  //                 .concat('')  //                 .concat(item.lastName);  //               return (  //                 <View style={styles.item} key={item.id}>  //                   <Thumbnail  //                     style={styles.thumbnail}  //                     source={{  //                       uri:  //                         'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',  //                     }}></Thumbnail>  //                   <Text style={styles.userName}>{userName}</Text>  //                   <View style={styles.addButtonContainer}>  //                     <Button  //                       rounded  //                       style={styles.addButton}  //                       onPress={() => {  //                         //addContact(Number(item.id));  //                         setIsSubmitted(false);  //                         setUserData(null);  //                       }}>  //                       <Icon  //                         name="plus"  //                         size={moderateScale(20)}  //                         color="black"  //                       />  //                     </Button>  //                   </View>  //                 </View>  //               );  //             },  //           )}  //         </View>  //       );  //     }  //   },  //   [createUserRelationMutation, userData],  // );  // const addContact = React.useCallback(  //   (id: Number) => {  //     console.log('Whats the Id', id);  //     createUserRelationMutation({  //       variables: {  //         input: { relatedUserId: id, type: RelationType.Contact, userId: 30 },  //       },  //     });  //   },  //   [createUserRelationMutation],  // );  const getContactId = React.useCallback(    (data: UsersLazyQueryHookResult) => {      //resetForm();      if (data) {        if (data.users.nodes.length == 0) {          Alert.alert('No User Found');        } else {          setUserData(data);        }      }    },    //[addContact],    [],  );  const [loadUsers] = useUsersLazyQuery({    onCompleted: getContactId,    onError: _onLoadUserError,  });  const handleSubmitForm = React.useCallback(    (values: FormValues) => {      setIsSubmitted(true);      const plusSign = '+';      const newPhoneNumber = plusSign.concat(values.phoneNumber);      loadUsers({        variables: {          where: { phoneNumber: newPhoneNumber },        },      });      resetForm();    },    [loadUsers],  );  // if (!addingContactLoading && isMutationCalled) {  //   if (addingContactError) {  //     Alert.alert('Unable to Add Contact');  //   }  // }  return (<SafeAreaView><View style={styles.container}><View style={styles.searchTopContainer}><View><View style={styles.searchFieldContainer}><View style={styles.form}><Item underline style={styles.newFieldInput} ><Icon name="mobile" color="black" size={26}></Icon><Input                       onChangeText={handleChange('phoneNumber') as (text: string) => void}                      onBlur={handleBlur('phoneNumber') as (event: any) => void}                      value={values.phoneNumber}                      placeholder="49152901820"                    /></Item></View><View style={styles.buttonContainer}><Button                  block                  success                  disabled={!isValid || !dirty}                  onPress={handleSubmit}                  style={styles.button}><Text>Speichern</Text></Button></View></View></View>          {/* {isSubmitted && showUsers(userData)} */}<User data={userData}></User></View></View></SafeAreaView>  );};
type UserProps = {   data: UsersLazyQueryHookResult;   //isSubmitted: boolean;  };  export const User: React.FunctionComponent<UserProps> = ({    data,    //isSubmitted,  }) => {console.log('user called');    const [      createUserRelationMutation,      {        data: addingContactData,        loading: addingContactLoading,        error: addingContactError,        called: isMutationCalled,      },    ] = useCreateUserRelationMutation({      onCompleted: () => {        Alert.alert('Contact Added');      },    });    const addContact = React.useCallback(      (id: Number) => {        console.log('Whats the Id', id);        createUserRelationMutation({          variables: {            input: { relatedUserId: id, type: RelationType.Contact, userId: 30 },          },        });      },      [createUserRelationMutation],    );      if (!addingContactLoading && isMutationCalled) {    if (addingContactError) {      Alert.alert('Unable to Add Contact');    }  }     //if (isSubmitted){      if(!data) return null;     return (<View style={styles.users}>          {data.users.nodes.map(            (item: { firstName: string; lastName: string; id: number }) => {              const userName = item.firstName                .concat('')                .concat(item.lastName);              return (<View style={styles.item} key={item.id}><Thumbnail                    style={styles.thumbnail}                    source={{                      uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',                    }}></Thumbnail><Text style={styles.userName}>{userName}</Text><View style={styles.addButtonContainer}><Button                      rounded                      style={styles.addButton}                      onPress={() => {                        addContact(Number(item.id));                        //setIsSubmitted(false);                        //setUserData(null);                      }}><Icon                        name="plus"                        size={moderateScale(20)}                        color="black"                      /></Button></View></View>              );            },          )}</View>      );}

But I have commented out setIsSubmitted(false); and setUserData(null);in the Usercomponent. How can I pass them such that they'll be updated in the original screen too?

Or is there a better way with which I can move out only the rendering list?

How to properly prevent TextInput blur on react-native?

$
0
0

In order to make a custom input, I had to create an InputWrapper to apply common style and add some animation behavior:

import React, { ReactElement, useState, useEffect } from 'react';import {  StyleSheet, View, TouchableWithoutFeedbackProps,} from 'react-native';import Text from './Text';import { Colors, Theme } from '../constants';import { TouchableWithoutFeedback } from 'react-native-gesture-handler';interface Props extends TouchableWithoutFeedbackProps {  label: string;  value?: any;  children: any;  focus: boolean;}const styles = StyleSheet.create({  // ...});const InputWrapper = ({  label, value, children, focus, ...props}: Props): ReactElement => {  const [show, setShow] = useState(false);  useEffect(() => {    setShow(focus || Boolean(value));  }, [focus, value])  return (<View      style={[        styles.container,        focus ? styles.containerFocus : {},      ]}><TouchableWithoutFeedback {...props}><View style={[          styles.wrapper,          focus ? styles.wrapperFocus : {},        ]}><Text            style={[              styles.label,              show ? styles.labelActive : {},            ]}>            {label}</Text>          {show && children}</View></TouchableWithoutFeedback></View>  );};export default InputWrapper;

I implemented the wrapper with the TextInput native component:

import React, { ReactElement, useState, useRef } from 'react';import {  TextInputProps, TextInput,} from 'react-native';import InputWrapper from './InputWrapper';import InputValue, { InputValueStyles } from './InputValue';interface Props extends TextInputProps {  label?: string;}const Input = ({  label, value, ...props}: Props): ReactElement => {  const [focus, setFocus] = useState(false);  const input = useRef(null);  const onWrapperPress = (): void => {    setFocus(true);  }  const onInputFocus = (): void => {    setFocus(true);  }  const onInputBlur = (): void => {    setFocus(false);  }  return (<InputWrapper      label={label}      value={value}      focus={focus}      onPress={onWrapperPress}>      {!focus && <InputValue value={value} />}      {focus && <TextInput        autoFocus={focus}        style={InputValueStyles.input}        value={value}        onFocus={onInputFocus}        onBlur={onInputBlur}        ref={input}        {...props}      />}</InputWrapper>  );};export default Input;

All works perfectly except one thing: If you press on the touchable overlay of the focuses input, you will lose this focus because it triggered the blur input event.

The question is quite simple then: How to prevent this?

I also tried other ways with the disabled prop of the touchable area or blur event preventing without any luck.

If you also have a better way to handle my need, I'm not against propositions. :-)


too many re-renders when data moved to a separate component

$
0
0

Currently, I am using this logic to render data on the basis of results from a grapqhl query. This works fine:

 const contacts = () => {    const { loading, error, data } = useUsersQuery({      variables: {        where: { id: 1 },      },    });    if (data) {      console.log('DATA COMING', data);      const contactName = data.users.nodes[0].userRelations[0].relatedUser.firstName        .concat('')        .concat(data.users.nodes[0].userRelations[0].relatedUser.lastName);      return (<View style={styles.users}><View style={styles.item} key={data.users.nodes[0].id}><Thumbnail              style={styles.thumbnail}              source={{                uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/girl_avatar_child_kid-512.png',              }}></Thumbnail><Text style={styles.userName}>{contactName}</Text></View></View>      );    }  };  return (<SafeAreaView style={{ flex: 1 }}><Container style={{ flex: 1, alignItems: 'center' }}><Item style={styles.addToWhitelist}><Icon name="add" onPress={() => navigation.navigate('AddContact')} /><Text style={styles.addToContactTitle}>Add contact</Text></Item><Text onPress={() => navigation.navigate('Home')}>Zurück</Text><View style={{ width: moderateScale(350) }}><Text>Keine Kontacte</Text></View>        {contacts()}        {/* <ContactList data={userData}></ContactList> */}</Container></SafeAreaView>  );};

However, when I make a separate component :

export const ContactList: React.FunctionComponent<UserProps> = ({  data,}) => {  console.log('user called');  if (!data) return null;  console.log('DATA COMING', data);      const contactName = data.users.nodes[0].userRelations[0].relatedUser.firstName        .concat('')        .concat(data.users.nodes[0].userRelations[0].relatedUser.lastName);  return (<View style={styles.users}><View style={styles.item} key={data.users.nodes[0].id}><Thumbnail        style={styles.thumbnail}        source={{          uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/girl_avatar_child_kid-512.png',        }}></Thumbnail><Text style={styles.userName}>{contactName}</Text></View></View>  );};

and call it like this:

 const [userData, setUserData] = useState<UsersQueryHookResult>('');  const contacts = () => {    console.log('running');    const { loading, error, data } = useUsersQuery({      variables: {        where: { id: 1 },      },    });    if (data) {      setUserData(data);    }  };  return (<SafeAreaView style={{ flex: 1 }}><Container style={{ flex: 1, alignItems: 'center' }}><Item style={styles.addToWhitelist}><Icon name="add" onPress={() => navigation.navigate('AddContact')} /><Text style={styles.addToContactTitle}>Add contact</Text></Item><Text onPress={() => navigation.navigate('Home')}>Zurück</Text><View style={{ width: moderateScale(350) }}><Text>Keine Kontacte</Text></View>        {/* {contacts()} */}<ContactList data={userData}></ContactList></Container></SafeAreaView>  );};

However, this gives me a too many re-renders issue. What am I missing? Probably something basic. I also tried using useEffects but I can't run a graphql query hook inside it. That gives me an invalid hook call error.

React question about geofire and useEffect

$
0
0

Hi I have question about react, I don't have much experience. I'm trying to do a query with geoFire and get the location, after that find the data in my db.

Geofire creates an event that I'am subscribed and send me the closest locations.

This moment I have query with geoFire and with an useEffect I do update in my state for caching the values.

Whent I update my state this action breaks geofire event and must start again from the beginning. So this is a problem? or is there a better solution ?

import React, {useState, useEffect} from 'react';import {View, Text} from 'react-native';import {GeoPosition, GeoError} from 'react-native-geolocation-service';import {getCurrentLocation, LocationInfo} from '../../util/geolocation';import GeoFireService from './services/GeoFireService';// import AdService from './services/AdService';// import { GeoQuery } from 'geofire';interface CurrentLocation {  [key: string]: {    location: [number, number];    distance: number;  };}const Ads = () => {  const [locationInfo, setLocationInfo] = useState({    latitude: 0,    longitude: 0,    altitude: 0,    accuracy: 0,  } as LocationInfo);  const [query, setQuery]: [GeoQuery | null, Function] = useState(null);  const [currentLocation, setCurrentLocation] = useState([] as Array<string>);  // set the current location  useEffect(() => {    getCurrentLocation(      (position: GeoPosition) => {        const {latitude, longitude, accuracy, altitude} = position.coords;        setLocationInfo({latitude, longitude, accuracy, altitude});      },      (err: GeoError) => {        console.log(err);      },    );  }, []);  // set the event query  useEffect(() => {    (async () => {      const geoFireQuery = await GeoFireService.getQuery(        [-34.5742746, -58.4744191],        30,      );      setQuery(geoFireQuery);      return () => geoFireQuery.cancel();    })();  }, []);  useEffect(() => {    if (query) {      (query as GeoQuery).on('key_entered',        (key: string, location: [number, number], distance: number) => {          if (!currentLocation.includes(key)) {            console.log(key);            setCurrentLocation([...currentLocation, key]);          }        },      );    }  });  return (<View><Text>        Latitude: {locationInfo.latitude} Longitude: {locationInfo.longitude}</Text>      {/* {Object.keys(currentLocation).map((key: string) => (<Text key={key}>          Ubicacion: {key}, Km: {currentLocation[key].distance.toFixed(2)}</Text>      ))} */}</View>  );};export default Ads;

This momento I have 3 location but this repeats too much. Console output should only show three locations

[Sun Jun 07 2020 20:06:14.990]  LOG      1wr0cDenn4DmJ8S0xraG[Sun Jun 07 2020 20:06:14.120]  LOG      58zvRXriUELSW96HprHh[Sun Jun 07 2020 20:06:14.121]  LOG      58zvRXriUELSW96HprHh[Sun Jun 07 2020 20:06:14.122]  LOG      58zvRXriUELSW96HprHh[Sun Jun 07 2020 20:06:14.134]  LOG      58zvRXriUELSW96HprHh[Sun Jun 07 2020 20:06:14.145]  LOG      1wr0cDenn4DmJ8S0xraG[Sun Jun 07 2020 20:06:14.158]  LOG      2Y5DBEsPQ1eFosxoAimB[Sun Jun 07 2020 20:06:14.159]  LOG      2Y5DBEsPQ1eFosxoAimB[Sun Jun 07 2020 20:06:14.160]  LOG      2Y5DBEsPQ1eFosxoAimB[Sun Jun 07 2020 20:06:14.174]  LOG      2Y5DBEsPQ1eFosxoAimB[Sun Jun 07 2020 20:06:14.187]  LOG      1wr0cDenn4DmJ8S0xraG[Sun Jun 07 2020 20:06:14.188]  LOG      58zvRXriUELSW96HprHh[Sun Jun 07 2020 20:06:14.189]  LOG      2Y5DBEsPQ1eFosxoAimB[Sun Jun 07 2020 20:06:14.198]  LOG      1wr0cDenn4DmJ8S0xraG[Sun Jun 07 2020 20:06:14.199]  LOG      2Y5DBEsPQ1eFosxoAimB[Sun Jun 07 2020 20:06:14.240]  LOG      2Y5DBEsPQ1eFosxoAimB[Sun Jun 07 2020 20:06:14.286]  LOG      1wr0cDenn4DmJ8S0xraG

Typescript not compiling as custom npm package

$
0
0

Actually I have a project hosted in Bitbucket, this project is using Typescript and is required by my react-native app in his package.json file from this way:

"@core": "git+https://bitbucket.org/agrostydevs/ag-core/src/master/",

@core project contains the following configuration on his tsconfig.json file:

{"compilerOptions": {"target": "es5","module": "commonjs","outDir": "./dist","skipLibCheck": true,"declaration": true,"lib": ["es6", "dom"],"removeComments": true,"isolatedModules": true,"strict": true,  },"include": ["lib"],"exclude": ["node_modules", "**/__tests__/*"]}

This is the package.json of @core project:

{"name": "core","license": "MIT","version": "1.0.0","main": "dist/index.js","author": "Germán Alzate","scripts": {"build": "tsc","prepare": "tsc"  },"devDependencies": {"typescript": "^3.2.2"  },"dependencies": {"@types/lodash": "^4.14.155","@types/node": "10.3.4","@types/react-redux": "^7.1.9","@types/redux": "^3.6.0","@types/redux-logger": "3.0.6","lodash": "^4.17.15","redux": "4.0.0","redux-logger": "3.0.6","redux-thunk": "^2.3.0"  }}

My project map directory on @core project is this.

- lib/    - actions/        - index.ts    - reducers/        - index.ts    - services/        - index.ts    - entities/        - index.ts    - common/        - index.ts    - config.ts    - index.ts- package.json- tsconfig.json

Son each time I call yarn upgrade @core on my react-native project, it does not compile on dist directory. When I log ls node_modules/@core/dist only appear the index.js requiring all other folders and files, but those files and folders does not appear so the app throws error trying to get those files

Can anyone help me? Any additional info just please comment

Pushing items into an array if dates matches - JavaScript/TypeScript

$
0
0

Shorting array to displayed them with respect to date, Like i did - Hiking, shopping on 2020-05-10 and Hiking , Football on 2020-05-10 and similar for other dates.

 const items = [ {title: 'Hiking', date: new Date('2020-05-10')}, {title: 'Shopping', date: new Date('2020-05-10')}, // {title: 'Hiking', date: new Date('2020-05-22')}, {title: 'Football', date: new Date('2019-05-22')}, // {title: 'Football', date: new Date('2020-05-28')}, {title: 'Hiking', date: new Date('2020-05-28')}, {title: 'Cricket', date: new Date('2020-05-28')},];

Fonts are not loaded when UI Kitten wants to use them in React Native project

$
0
0

I am using the UI Kitten library in a React Native project with Typescript.
I've created a mapping.json and a react-native.config.js file which look like this:

  • mapping.json:

    {"strict": {"text-font-family": "OpenSans-Regular","text-heading-1-font-size": 30,"text-heading-1-font-weight": "800","text-heading-1-font-family": "OpenSans-Bold","text-subtitle-1-font-size": 15,"text-subtitle-1-font-weight": "600","text-subtitle-1-font-family": "OpenSans-ExtraBoldItalic","text-paragraph-1-font-size": 12,"text-paragraph-1-font-weight": "400","text-paragraph-1-font-family": "OpenSans-Light","text-caption-1-font-size": 12,"text-caption-1-font-weight": "400","text-caption-1-font-family": "OpenSans-Regular","text-label-font-size": 12,"text-label-font-weight": "800","text-label-font-family": "OpenSans-SemiboldItalic"   }}
  • react-native.config.js:

     module.exports = {   project: {   ios: {},   android: {},   },   assets: ['./assets/fonts'], };

My custom fonts are located under the assets/fonts folder and I've executed the npx react-native link command.

I am getting the following error message:enter image description here

If I click on Dismiss the application is working correctly I think the fonts are not loaded only when the application starts.

I tried loading the fonts like this in my App.tsx, didn't help:

 const App = (): JSX.Element => { const [assetsLoaded, setAssetsLoaded] = useState(false); useEffect(() => {   async function importFonts() {     await Font.loadAsync({'openSans-bold': require('../assets/fonts/OpenSans-Bold.ttf'),'openSans-bold-italic': require('../assets/fonts/OpenSans-BoldItalic.ttf'),'openSans-extra-bold': require('../assets/fonts/OpenSans-ExtraBold.ttf'),'openSans-extra-bold-italic': require('../assets/fonts/OpenSans-ExtraBoldItalic.ttf'),'openSans-italic': require('../assets/fonts/OpenSans-Italic.ttf'),'openSans-light': require('../assets/fonts/OpenSans-Light.ttf'),'openSans-light-italic': require('../assets/fonts/OpenSans-LightItalic.ttf'),'openSans-regular': require('../assets/fonts/OpenSans-Regular.ttf'),'openSans-semi-bold': require('../assets/fonts/OpenSans-Semibold.ttf'),'openSans-semi-bold-italic': require('../assets/fonts/OpenSans-SemiboldItalic.ttf'),  });}importFonts().catch((error) => {  console.error(error);});setAssetsLoaded(true);}, []); if (assetsLoaded) {return (<><IconRegistry icons={EvaIconsPack} /><ApplicationProvider {...eva} theme={{ ...eva.light, ...theme }} customMapping={mapping}><NavigationContainer><TabNavigator /></NavigationContainer></ApplicationProvider></>);}  return (<ApplicationProvider {...eva} theme={{ ...eva.light, ...theme }}><Text>Loading</Text></ApplicationProvider>  );};

I am also getting a Property 'components' is missing in type ... on customMapping={mapping} I don't know if that relates to this problem.
I've reviewed all of the SO questions and github issues related to this, nothing helped.
I've also ran expo r -c, deleted node_modules and ran yarn install again, nothing helped, I am quite lost.

Viewing all 6219 articles
Browse latest View live


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