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

React Native Typescript Not Recognizing .d.ts Files

$
0
0

I am writing a reac-native app, created from the typescript template. When I create a file for types, lets call it fragmentTypes.d.ts and try to import it using the standard import {MyType} from './fragmentTypes' I get an error saying

error: Error: Unable to resolve module `./fragmentTypes` from `src\Pages\Login\Fragments\index.ts`:None of these files exist:  * src\Pages\Login\Fragments\fragmentTypes(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)  * src\Pages\Login\Fragments\fragmentTypes\index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)

It works when I try and import fragmentTypes.d, but obviously that isn't the best solution. How do I change what file types its looking for and add d.ts?


React Native Array Notation with Typescript

$
0
0

I have an object that I am trying to pass a style to. With regular JS I can pass

<ObjectName         containerStyle={[    {marginTop: 10, marginBottom: 30},    {borderBottomWidth: 3},     keyboardOpen ? null : {marginHorizontal: 30},  ]} />

However when I try to do the same thing in Typescript I get the error that the given objects have no properties in common with FlexStyle, Object is delcared as follows

export const ObjectName = (props: {containerStyle?: FlexStyle}) => {...}

How would I combine those styles with array notation in TS, or if I can't what would be the best method to use?

TypeScript not recognising global variables from tests setup

$
0
0

I am appending some common functions to the global object in my setupTests.ts so I don't need to import them in every test file. The tests are passing, but TypeScript autocompletion is not working and VSCode shows "Cannot find name ...". How can I fix it?

package.json

"jest": {"preset": "jest-expo","roots": ["<rootDir>/src"  ],"setupFiles": ["<rootDir>/src/config/setupTests.ts"  ]}

setupTests.ts

import React from 'react';import { render } from 'react-native-testing-library';global.React = React;(global as any).render = render;

some.test.tsx

const wrapper = render(<Text>Some test</Text>);

enter image description here

How can I specify the height in react project?

$
0
0

Happy Friday.

I've tried putting the following in options but none seem to make any change.

"height": "100%""height": "450px""height": "auth"

I prefer not to change in css. only react component.How can I set the height?

Thanks.

ReactJs calculate sum of all values present in Table column

$
0
0

I am having a Bootstrap-table rendering values from service called in componentDidMount().

Example of my table -

  Col1      Col2 Col3   1         2    3   4         5    6   7         8    9  SumValue  15   18 //This last row holds sum of all values

How to calculate SumValue of all the values present in col1 and display in Footer.

Below is the code how i am using react-row for mapping data to rows. And value is the variable holding data of all columns present in json file returned from service, after setting it to the component's state.

    {this.state.value && this.state.value.map(function (value, ind) {                    return <Row key={ind} item={value}></Row>                })            }

Initializing state

   constructor(props){    super(props)    {        this.state ={            value: [],   //Initializing an array            SumValue: '',            default: false,                       }                }

Setting state

  fetch('https://www.serviceUrl.com')   .then(res => res.json())    .then(value => {        this.setState({            value: value.empRecords,  //Here its getting all records from json            default: false        });            })

Let me know guys if any more information is required.

Navigation from within a HOC in React Native

$
0
0

I wish to add a check to every page in my app. The check is that if a file exists then pull the user to a page.

I think that a HOC is one way to do this (are there others?)

and I have come up with this

import React from "react";import { NavigationScreenProp } from "react-navigation";import RNFS from "react-native-fs";interface MyComponentProps {  navigation: NavigationScreenProp<any, any>;}interface MyComponentState {}const importFileCheck = WrappedComponent => {  class HOC extends React.Component<MyComponentProps, MyComponentState> {    constructor(props) {      super(props);      this.props.navigation.addListener("didFocus", () => {        RNFS.exists(".\path\I\care\about.xml"        ).then(exists => {          if (exists) {            this.props.navigation.navigate("Export");                         }        });      });    }    render() {      return <WrappedComponent {...this.props} />;    }  }  return HOC;};export default importFileCheck;

When I run the page I get an error

TypeError: undefined is not an object (evaluating this.props.navigation.addListener)

So I guess that the navigation 'thing' is not being passed through properly

For completion I use the HOC like so

importFileCheck(App) 

and App has the navigation stuff already in it, and works without the HOC.

Imports are

"react": "16.6.1",
"react-native": "0.57.7",
"react-navigation": "3.2.0"

Further details for the keen :D

First I make a stack navigator that is all the pages in my app

const appNav = createStackNavigator(    {        Calculator: {            screen: Calculator,            navigationOptions: { title: "Calculator" }        },   // more pages);export default createAppContainer(appNav);

In App.tsx

this gets 'wrapped' in other components

const WrappedStack = () => {  return <RootStack screenProps={{ t: i18n.getFixedT() }} />;};const ReloadAppOnLanguageChange = translate("translation", {  bindI18n: "languageChanged",  bindStore: false})(WrappedStack); class App extends React.Component {  public render() {    return (<I18nextProvider i18n={i18n}><StyleProvider style={getTheme(material)}><Provider            ManureStore={ManureStore}            SettingsStore={SettingsStore}            FieldStore={FieldStore}            CalculatorStore={CalculatorStore}            FarmStore={FarmStore}><ReloadAppOnLanguageChange /></Provider></StyleProvider></I18nextProvider>    );  }}

and finally we wrap with my new HOC

export default importFileCheck(App) 

key extractor type in TypeScript FlatList

$
0
0

Previously, I was using a React Native FlatLis like this. Here datais obtained via a graphql query:

 return (<SafeAreaView><View><View style={styles.searchTopContainer}><View style={styles.searchTopTextContainer}><Text              style={styles.searchCancelResetText}              onPress={() => {                setUserData(null);                navigation.goBack();              }}>              Cancel</Text></View><View style={styles.listHolder}>            {data && (<FlatList                data={data.users.nodes}                horizontal={false}                scrollEnabled                renderItem={({ item }) => (<User                    user={item}                    originatorId={route.params.originatorId}                    //onSendRequest={onSendRequest}                  />                )}                keyExtractor={(item) => item.id.toString()}                ListEmptyComponent={NoFriendsContainer}              />            )}</View></View></View></SafeAreaView>  );

This worked fine and didn't give any errors. However, now I am trying to make a separate component FlatList which returns a FlatList only (under a View).

export const FlatList: React.FunctionComponent<UserProps> = ({  data,  originatorId,}) => {  return (<View><FlatList        data={data.users.nodes}        horizontal={false}        scrollEnabled        renderItem={({ item }) => (<User            user={item}            originatorId={originatorId}            //onSendRequest={onSendRequest}          />        )}        keyExtractor={(item) => item.id.toString()}        ListEmptyComponent={NoFriendsContainer}      /></View>  );};

I get errors on the horizontal property that:

Type '{ data: any; horizontal: boolean; scrollEnabled: true; renderItem: ({ item }: { item: any; }) => Element; keyExtractor: (item: any) => any; ListEmptyComponent: FunctionComponent<{}>; }' is not assignable to type 'IntrinsicAttributes & UserProps & { children?: ReactNode; }'.  Property 'horizontal' does not exist on type 'IntrinsicAttributes & UserProps & { children?: ReactNode; }'.ts(2322)

Similarly, I get an error on item from keyExtractor and renderItem that

Parameter 'item' implicitly has an 'any' type.

How can I fix this? I am using the code for the FlatList in both codes then why do I see an error in the second case and not the first one?

RN Error: Text strings must be rendered within a component

$
0
0

I know this question has been asked before but none of the answers helped me. I am getting this error in a file which contains this:

<View style={styles.listHolder}>            {data && (<MyList data={userData} onSendRequest={onSendRequest}></MyList>            )}</View>

Here data is returned by a grapqhl query (Apollo). The error is somewhere in the MyList component which looks like this:

type UserProps = {  data: UsersLazyQueryHookResult;  //originatorId: number;  onSendRequest: (id: number) => void;};export const MyList: React.FunctionComponent<UserProps> = ({  data,  //originatorId,  onSendRequest,}) => {  return (<View>      {data && (<FlatList          data={data.users.nodes}          horizontal={false}          scrollEnabled          renderItem={({ item }) => (<User              user={item}              onSendRequest={onSendRequest}            />          )}          keyExtractor={(item) => item.id.toString()}          ListEmptyComponent={NoFriendsContainer}        />      )}</View>  );};

In this component, the error falls somewhere on the first line of the return which says <View>

What am I missing out? Note that the brackets before MyList come automatically when I use Prettier for formatting.


conditionally render some items from React-Native FlatList

$
0
0

I am using the React Native FlatList like this:

export const UserList: React.FunctionComponent<UserListProps> = ({  data,  onSendRequest,}) => {  return (<View><FlatList        data={data?.users?.nodes}        horizontal={false}        scrollEnabled        renderItem={({ item }) => (<User user={item} onSendRequest={onSendRequest} />        )}        keyExtractor={(item) => item?.id?.toString()}        ListEmptyComponent={NoUsersContainer}      /></View>  );};

Currently, it renders all items. Is there any way I can introduce some sort of checks inside the Flatlist? For instance, if

data.users.nodes.id == 1

then don't render while all the rest should be rendered. Generally we could do something like this with a ternary operator or if-else statements but I couldn't think of a clean, correct way for FlatLists.

How to pass multiple mobx observer states into function as parameter

$
0
0

I have these states:

  @observable questionString: string = '';  @observable questionLengthRemaining: number = 25;  @observable descriptionString: string = '';  @observable descriptionLengthRemaining: number = 500;

And i have this function:

onInputChamge = (state: any, stateLengthRemaining: any, maxLength: any, text: string) => {    state = text;    stateLengthRemaining = maxLength - text.length;  }

And here is my component:

<TextInput            multiline={true}            maxLength={questionMaxLength}            placeholder='Type your question here'            style={styles.questionInput}            onChangeText={(question) => this.onInputChamge(this.questionString, this.questionLengthRemaining, questionMaxLength, question)}          />

I have multiple textInputs that just need to do the same thing and take in the onInputChange function, but with just different states and lengths. For some reason, passing in the states as parameters in the function does not work, but when I create different functions for each of them like:

onQuestionChange = (text: string) => {    this.questionString = text;    this.questionLengthRemaining = maxQuestionLength - text.length;  }

It works.

It's super pointless to make the same function for each input, because that's what functions are supposed to limit. I'm using typescript and mobx by the way. Any way to do this? (If i console log the length remaining, it prints out correct numbers and strings so idk what is going on)

How to do component inheritance in React Native like on native platform?

$
0
0

My background is an iOS developer and in swift I could do MyInput: UITextField (swift component alternative to React Native Input).This meant that MyInput automatically got all the properties and functions that UITextField has. Currently in react native I do this like this:

interface Props {    title?: string;    text: string;    onChangeText?: (string) => void;    keyboardType?: KeyboardTypeOptions;    disabled?: boolean;    onBlur?: () => void;}export default function MyInput ({    title, text, onChangeText, keyboardType, disabled = false, onBlur= (()=> null)}: Props){return(<Input        label={title}        onChangeText={(text) => onChangeText(text)}        value={text}        keyboardType={keyboardType}        disabled={disabled}        onBlur={() => onBlur()}    />);

Basically I have to add anything I want from Input into Props and then redirect it into Input. Is there a way that I could just upgrade Input without doubling most of the code and to have all the Input properties by default available in MyInput?

So methods like onBlur would have to be rewritten.

Or if anyone at least could tell me what to google to find such solution?

Modal in stackNavigator react native expo

$
0
0

so I have an issue with stacknavigator on an expo app and trying to open a modal from it.

If the modal is on the body of the app, it works fine, with no issue, but when the modal is launched from a stack screen, most of the view is missing and when inspecting, the content is there and clickable, just not shown.

I've added a screenshot of what I mean.

It's the same piece of code for both.

This is how I added the modal to the stack

return (<Stack.Navigator  screenOptions={headerOptions}  headerMode="screen"  initialRouteName={'Home'}><Stack.Screen    name="Home"    component={TabNavigator}    options={({ navigation, route }) => {      let tabScene = getTabSceneName(route);        return {          headerTitle:<View><TouchableOpacity                onPress={() => setSearchModalVisible(true)}                activeOpacity={1}><View style={styles.searchInputContainer}><SearchInput                    pointerEvents="none"                    placeholder={t('Search')}                    editable={false}                  /></View></TouchableOpacity><SearchModal                onItemPress={(product: Product) => {                  navigation.navigate('ProductDetails', { productHandle: product.handle });                }}                onSubmit={(searchKeyword: string) =>                  navigation.navigate('SearchResults', {                    searchKeyword,                  })                }                isVisible={isSearchModalVisible}                setVisible={setSearchModalVisible}              /></View>,          headerRight: () => (<HeaderIconButton              icon="cart"              onPress={() => navigation.navigate('ShoppingCart')}            />          ),          headerStyle: {            shadowColor: COLORS.transparent,            elevation: 10,          },        };      }    }}  /><Stack.Screen    name="Auth"    component={AuthScene}    options={() => ({      title: t('Welcome'),    })}  /><Stack.Screen    name="ForgotPassword"    component={ForgotPasswordScene}    options={() => ({      title: t('Forgot Password'),    })}  /></Stack.Navigator>);}

I've attached screenshots of how it's meant to be like and the issue.

Screenshot of missing view, when it's launched from the stack screen

Screenshot of how it's meant to look like

Transparent images not showing in Image component

$
0
0

Trying to display an image that has a transparent background on an expo app (code is below) but it doesn't seem to want to show. It takes up the given dimensions but the actual image is not showing. The file format is png

Tested it with a jpg, transparent background is now white - works without any issues.

<Image   source={require('../../assets/categoryIcons/Hotpot.png')}   style={{height: 52, width:52}}/>

Is this a bug? or is there something that's I'm completely missing?

I am trying to use React$Node in react native class but i am unable to do this things i gets errors

$
0
0

this is my code actually I get user login details recharge from laravel api. this code is working fine if I use it without class component but my app has bottom navigation and i am bound to write this code in class component. Needs suggestions how to achieve this kind of functionality or if it's impossible to use React$Node and class component together then give me some suggestions how to do this kind of functionality within the class.

export default class Together extends React.Component {        App: () => React$Node = () => {        const [mtag_id,setmtag_id] = useState();        validateUser = async()=>{          await fetch('http://server_ip/api/v1/user/login'          ,{            method:'POST',            headers:{'Accept': 'application/json',              //'Content-Type': 'application/x-www-form-urlencoded''Content-Type': 'application/json'            },            body: JSON.stringify({"email":'abc@yahoo.com',"password": 'abc123'}),          }).then(loginres => loginres.json())          .then(loginresData =>{            //alert(resData.token);            if(loginresData.status == '200')            {              //alert('OK')              //alert(resData.token)              //////////////////////start getInfo api////////////////////////////////             fetch('http://server_ip/api/v1/recharge/getInfo'             ,{              method:'POST',              headers:{'Accept': 'application/json',              //'Content-Type': 'application/x-www-form-urlencoded''Content-Type': 'application/json','Authorization': loginresData.token,            },            body: JSON.stringify({"mtag_id": mtag_id}),                }).then(infores => infores.json())            .then(inforesData=> {              //this.props.navigation.navigate("recharge")              if(inforesData.status == '200'){                //alert('OK')                //this.props.navigation.navigate("recharge")              ///////////////recharge api start////////////////////////              fetch('http://server_ip/api/v1/recharge/account',{              method:'POST',              headers:{'Accept': 'application/json',              //'Content-Type': 'application/x-www-form-urlencoded''Content-Type': 'application/json','Authorization': loginresData.token,            },            body: JSON.stringify({"mtag_id": mtag_id , "amount": '299'}),                }).then(rechargeres => rechargeres.json())            .then(rechargeresData =>{              if(rechargeresData.status == '200'){                alert(rechargeresData.msg)              }              else{                alert(rechargeresData.status)              }            ////////////////recharge api end//////////////////////              console.log(rechargeresData)            });              }              else{                alert(inforesData.status)              }              console.log(inforesData);            });            }            //////////////////////////////////end getInfo api///////////////////////////            ///////login else////////            else            {              alert(loginresData.status);            }            console.log(loginresData);          });        }        }        render(){          return (<Container><Content><Header><Title>                  Smart Motorway</Title></Header><CardItem header><Text style ={styles.heading}>M-Tag Recharge</Text></CardItem><CardItem><Input placeholder = "M-Tag ID" style={styles.input}                value = {mtag_id} onChangeText={(value) => setmtag_id(value)}                /></CardItem><CardItem><Body><Button primary block onPress = {validateUser}><Text style = {styles.btn}>Recharge</Text></Button></Body></CardItem></Content></Container>          );        }    }

Extending react-native-paper components in TypeScript

$
0
0

I'm struggling to extend the react-native-paper components correctly. What am I doing wrong or how to do it correctly? actually, I'm not totally new to Typescript, but I always struggled with this one:

// TextInput.tsximport React from "react";import { TextInput as PaperTextInput } from "react-native-paper";import { TextInputProps } from "react-native-paper/lib/typescript/src/components/TextInput/TextInput";interface MyTextInputProps extends TextInputProps {}const MyTextInput: React.FC<MyTextInputProps> = (props) => {  return <PaperTextInput {...props} />;};export default MyTextInput;
// Usage:<TextInput mode="outlined" style={styles.input} label="Email" />

And I get this error:

Property 'theme' is missing in type '{ mode: "outlined"; style: { alignSelf: "stretch"; }; label: string; }' but required in type 'MyTextInputProps'


Disable only horizontal scrolling in FlatList

$
0
0

How can I disable only horizontal scrolling on my FlatList? Putting it to false doesnt work. I want to be able to scroll it vertically but not horizontally.

<FlatList              data={data.me.friends.nodes}              //horizontal={false}              //scrollEnabled={false}              renderItem={({ item }) => (<FriendItem friend={item} originatorId={data.me.id}/>              )}              keyExtractor={(item) => item.id.toString()}              ListEmptyComponent={NoFriendsContainer}            />            ```

draw a vertical line between 2 objects

$
0
0

Is it possible to draw a vertical line between 2 text objects? I looked into this but this is not exactly what I need:

https://reactjsexample.com/draw-a-line-between-two-elements-in-react/

enter image description here

<View style={styles.ridesFriends}><Text style={styles.numbers}>132    </Text><Text style={styles.numbers}>{numberOfFriends}</Text></View>
  ridesFriends: {    paddingTop: 70,    alignItems: 'center',    flexDirection: 'row',    justifyContent: 'space-evenly',    width: '100%',  },  numbers: {    fontSize: 30,    color: '#31C283',    fontWeight: 'bold',  },

Edit:

I tried adding a view in between the two numbers:

  verticleLine:{    height: '100%',    width: 1,    backgroundColor: '#909090',  },
<View style={styles.ridesFriends}><Text style={styles.numbers}>132</Text><View style={styles.verticleLine}></View><Text style={styles.numbers}>{numberOfFriends}</Text></View>

but it's not in the centerenter image description here

Saving something in app object to address it within the components

$
0
0

I remember it is somehow possible to access to the application instance within any of the react native components. How to actually do that?

Asking this because sometimes it seems to be more convenient than storing some objects in custom global storage or in the AsyncStorage, for example.

The hypothetical example of what I am asking:

class SomeComponent extends Component {    constructor(props) {        super(props);        this.Application.some_object_saved_as_an_attribute_of_the_application.doStuff();    }}

FlatList moves/drags in all directions

$
0
0

When I click on my FlatList I can drag and move it in all directions (up/down/right left). Although the list appears to be vertical (maybe because of the styling), the scroll bar still appears horizontally. How can I disable this dragging?

This is how I am using the FlatList:

<FlatList              data={data.me.friends.nodes}              //horizontal={false}              //scrollEnabled={false}              renderItem={({ item }) => (<FriendItem friend={item} originatorId={data.me.id}/>              )}              keyExtractor={(item) => item.id.toString()}              ListEmptyComponent={NoFriendsContainer}            />

This is from the FriendItem's return

  return (<View style={styles.item}><TouchableOpacity        onPress={() =>          navigation.navigate('FriendDetails')        }><Thumbnail          style={styles.thumbnail}          source={{            uri:'https://cdn4.iconfinder.com/person-512.png',          }}></Thumbnail></TouchableOpacity><View style={styles.nameContainer}><Text style={styles.userName}>{userName}</Text></View><View style={styles.deleteButtonContainer}><Button          rounded          style={styles.deleteButton}          onPress={() => onDeleteFriend(originatorId, friend.id)}><Icon name="trash-o" size={moderateScale(20)} color="black" /></Button></View></View>  );};

Styles for FriendItem:

export const styles = StyleSheet.create({  item: {    backgroundColor: 'white',    borderRadius: moderateScale(20),    padding: moderateScale(20),    marginVertical: moderateScale(8),    marginHorizontal: 16,    height: moderateScale(110),    width: moderateScale(360),    justifyContent: 'space-between',    flexDirection: 'row',  },  userName: {    paddingRight: 55,    paddingLeft: 10,    paddingTop: 20,  },  deleteButton: {    backgroundColor: '#31C283',    width: moderateScale(45),    justifyContent: 'center',  },  deleteButtonContainer: {    paddingTop: 12,    marginRight: 2,  },  thumbnail: {    height: 85,    width: 85,    marginLeft: 2,    paddingRight: 0,    position: 'relative',  },  nameContainer: {    flexDirection: 'row',  },});

I also tried removing the TouchableOpacity but it made no difference.

Query Doesn't Re-run after navigation

$
0
0

I have a screen where I am using a query like this:

export const AllFriends: React.FunctionComponent = () => {  const navigation = useNavigation();  const { data, error } = useGetMyProfileQuery({    onCompleted: () => {      console.log('hellooo')    },  });

Every time I visit this page from the home-page, I think the query re-runs as I always see the hellolog. Similarly, from this page, I visit another screen like this:

<Text            onPress={() => navigation.navigate('PendingRequests')}>            Pending Requests (            {data              ? data.me.pendingUserRelationsRequestsReceived.totalCount              : ''}            )</Text>

Every time I visit this screen, I see the hellooo from pending again. This screen looks like this:

export const ReceivedPendingRequests: React.FunctionComponent = () => {  const navigation = useNavigation();  const { data, error } = useGetMyProfileQuery({    onCompleted: () => {      console.log('hellooo from pending')    },  });  return (<SafeAreaView style={styles.safeView}><Container style={styles.container}><Text          style={styles.backText}          onPress={() => navigation.navigate('AllFriends')}>          Zurück</Text></Container></SafeAreaView>  );};

Now the problem is that when I navigate back to AllFriends, the query should re-run and I should see the hello log again just like I see when I come from the Homepage to AllFriends. But I don't.

However, if I come back from AllFriends to PendingRequests, I see the log hellooo from pending again.

Edit:

  useFocusEffect(()=>{    getMyProfile()  },[]);  const getMyProfile = () => {    const { data, error } = useGetMyProfileQuery({      onCompleted: () => {        console.log('hellooo')      },      //fetchPolicy: 'network-only',    });  }
Viewing all 6218 articles
Browse latest View live


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