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

Ionic React: How do you implement the ionic refresh to load a list with more added items

$
0
0

I am having difficulty trying to implement an ionic refresher to my app so once you pull down on refresh the page will add more to the current list on the page. I have added snippets of my original notifications page along with the Ionic Docs refresher component. If anyone knows how to implement this correctly it would be much appreciate as their is no examples for the solution when it comes to Ionic React and Typescript.

Here is the Ionic Refresher component from react which I am having issues trying to implement.

import React from 'react';import { IonContent, IonRefresher, IonRefresherContent } from '@ionic/react';import { RefresherEventDetail } from '@ionic/core';import { chevronDownCircleOutline } from 'ionicons/icons';function doRefresh(event: CustomEvent<RefresherEventDetail>) {  console.log('Begin async operation');  setTimeout(() => {    console.log('Async operation has ended');    event.detail.complete();  }, 2000);}export const RefresherExample: React.FC = () => (<IonContent>    {/*-- Default Refresher --*/}<IonContent><IonRefresher slot="fixed" onIonRefresh={doRefresh}><IonRefresherContent></IonRefresherContent></IonRefresher></IonContent>    {/*-- Custom Refresher Properties --*/}<IonContent><IonRefresher slot="fixed" onIonRefresh={doRefresh} pullFactor={0.5} pullMin={100} pullMax={200}><IonRefresherContent></IonRefresherContent></IonRefresher></IonContent>    {/*-- Custom Refresher Content --*/}<IonContent><IonRefresher slot="fixed" onIonRefresh={doRefresh}><IonRefresherContent          pullingIcon={chevronDownCircleOutline}          pullingText="Pull to refresh"          refreshingSpinner="circles"          refreshingText="Refreshing..."></IonRefresherContent></IonRefresher></IonContent></IonContent>);

**

Below is one of my Notifications page where I intend to add the "IonRefresher".

import React, { useContext } from "react";import {  IonHeader,  IonContent,  IonToolbar,  IonTitle,  IonPage,  IonList,  IonItem,  IonLabel,  IonIcon,} from "@ionic/react";  return (<IonPage><IonHeader><IonToolbar><IonTitle>Notifications</IonTitle></IonToolbar></IonHeader><IonContent><IonList><IonItem><IonLabel><h2>Thank you for applying to...</h2><p>We hope to get in touch with you soon about...</p></IonLabel><IonIcon slot="end" icon={sendOutline} /></IonItem><IonItem><IonLabel><h2>You have started following...</h2></IonLabel><IonIcon slot="end" icon={logoTwitter} /></IonItem></IonList></IonContent></IonPage>  );};export default Notifications;

View hidden by inner view

$
0
0

I have wrapped my content in a SafeAreaView and then another View component. However, the SafeAreaView and View both are somehow hidden/overwritten by the secondary View which has the style of the containerTop

Here, the SafeAreaView (red) shows up at the bottom but not at the top. Similarly if I add a background color to the top most View, I don't see any change on the screen. I tried to add zIndex:1 but it doesn't work. At the top, the backgroundColor from the containerTop covers up the entire area.

enter image description here

export const Screen: React.FunctionComponent = () => {  return (<SafeAreaView style={styles.safeContainer}><View style={styles.container}><View style={styles.containerTop}><BackArrow /><JourneyLocationsTextContainer /><View style={styles.containerOptionsSelector}><TripOptionsSelector /></View></View><View style={styles.containerMap}><MapContainer /><ButtonsContainer /></View></View></SafeAreaView>  );};const styles = StyleSheet.create({  safeContainer: { flex: 1, backgroundColor: 'red' },  container: { backgroundColor: 'white', flex: 1 },  containerTop: { flex: 1, backgroundColor: '#323443' },  containerOptionsSelector: {    marginTop: moderateScale(20),    marginLeft: moderateScale(20),  },  containerMap: { flex: 2 },});Navigation:<NavigationStack.Screen        name="Screen"        component={Screen}        options={{          headerShown: false,          gestureEnabled: false,          cardStyleInterpolator:            CardStyleInterpolators.forFadeFromBottomAndroid,        }}      />

How can I fix this? Why is the View and SafeAreaView not showing up at the top?

rows with overlapping text/icons in Android

$
0
0

I have a screen where I map some icons and text as rows. It works perfectly fine in iOS but everything overlaps in Android. I have already tried using lineHeight as suggested by some other answers but it doesn't work. How can I fix this?

The list is rendered in the FilterCriteriaList component.

  return (<View style={styles.container}><View style={styles.horizontalLine} />      {criteriaList.map((item: CriteriaList, index: number) => (<View key={index}><View style={styles.criteriaRow}><Icon              name={item.checked ? 'dot-circle-o' : 'circle-thin'}              color="#31C283"              size={moderateScale(20)}/><Text style={styles.text}>{item.title}</Text></View><View style={styles.horizontalLine} /></View>      ))}</View>  );};const styles = StyleSheet.create({  container: {    flex: 1,  },  criteriaRow: {    flexDirection: 'row',    paddingLeft: moderateScale(25),    alignItems: 'center',  },  horizontalLine: {    width: '100%',    height: moderateScale(1),    backgroundColor: '#f0f0f0',  },  text: {    paddingLeft: moderateScale(15),    paddingBottom: moderateScale(15),    marginBottom: moderateScale(15),    paddingTop: moderateScale(15),  },});
<View style={styles.filterCriteriaContainer}><Text style={styles.greyHeadingText}>Weitere Filter</Text><FilterCriteriaList/></View>  filterCriteriaContainer: {    paddingTop: moderateScale(35),    zIndex: 1,  },

Android:enter image description here

iOS:enter image description here

unable to scroll list in android with keypad

$
0
0

On my screen, I search items using the input field. The list that is rendered is inside a ScrollView but it does not let me scroll in Android at least. How can I fix this?

Maybe its because of the keypad.

  return (<>      {addressesFound.length > 0 ? (<ScrollView          style={styles.searchResultsContainer}          keyboardShouldPersistTaps={'always'}          keyboardDismissMode={'on-drag'}>          {addressesFound.map((addressDetails: addressDetailsType) => {            return (<View                key={addressDetails.placeName}                style={styles.resultContainer}><Text                  style={styles.text}>                  {addressDetails.placeName}</Text></View>            );          })}</ScrollView>      ) : null}</>  );};const styles = StyleSheet.create({  searchResultsContainer: {    width: moderateScale(400),    paddingHorizontal: moderateScale(50),    paddingRight: moderateScale(65),    marginTop: moderateScale(10),  },  resultContainer: {    marginTop: moderateScale(10),    borderBottomWidth: 1,    borderBottomColor: 'grey',  },  text: {    fontSize: moderateScale(15),  },});

enter image description here

Possible Unhandled Promise Rejection (id: 0) Error: timeout of 0ms exceeded

$
0
0

I want to show the total number of connections I have using the API I created, but when I run with the mobile project, the results show only '0' and show this error message. It should automatically display the number of connections on the screen, I already tested it with the web application and it works, the problem persists only in the mobile version. In the api.ts file the URL is in this format because I am simulating the mobile application on an iOS device with a DevTools connection through the Tunnel.

My api.ts for connetion with api

import axios from "axios";const api = axios.create({    baseURL: "http://y7-xkq.anonymous.mobile.exp.direct:3333",});export default api;
const [totalConnections, setTotalConnections] = useState(0);    useEffect(() => {        api.get("connections").then((response) => {            // console.log(response);            const { total } = response.data;            setTotalConnections(total);        });    }, []);
<Text style={styles.totalConnections}>    Total de {totalConnections} conexões já realizadas{" "}<Image source={heartIcon} /></Text>

How to import React-Native types via Typescript for Flow?

$
0
0

In my react-native application I have a TextInput component. The TextInput reads some types from the following path:

/Users/karl/Library/Caches/typescript/3.6/node_modules/@types/react-native/index.d.ts

This file has a bunch of types in including:

export type KeyboardType = 'default' | 'email-address' | 'numeric' | 'phone-pad';

I can access this file by cmd + clicking on a prop I have added, (using vscode) to go to it's definition.

What I am wondering though is how I can reference the types in this file, so I can use them in my Flow typing definitions?

I want to be able to do something like:

// pseudocodeimport type { KeyboardType } from 'react-native'

How I can go about this?

What's the right configuration for testing using jest for a project that uses linked modules that include peerDependencies to parent?

$
0
0

I'm working with a Typescript Expo projectA and a libB that is npm linked from projectA.

  • LibB has react-native and some other RN related libs as peerDependencies and devDependencies.
  • ProjectA has the libB peer dependencies installed properly (react-native and so on)

The project works fine with a modified metro config to make it take into account the linked libB and peerDependencies, but for the Jest tests it fails with the next error:

Invariant Violation: __fbBatchedBridgeConfig is not set, cannot invoke native modulesat invariant (../libB/node_modules/invariant/invariant.js:40:15)      at Object.<anonymous> (../libB/node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:166:3)      at Object.<anonymous> (../libB/node_modules/react-native/Libraries/TurboModule/TurboModuleRegistry.js:13:23)

It's clear from the error that the problem is Jest is loading and trying to use the react-native version from the libB node_modules but what I want is Jest to use the one from projectA. I tried to configure the projectA jest.config.js (created at projectA's root dir) to make it exclude the libB node_modulues/react-native lib but it's not working.

this is my projectA/jest.config.js:

module.exports = {  preset: "jest-expo",  modulePathIgnorePatterns: ["<rootDir>/node_modules/libB/node_modules/react-native",  ],  transformIgnorePatterns: ["<rootDir>/node_modules/libB/node_modules/((react-native|invariant)/)","<rootDir>/node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@sentry/.*)",  ],  verbose: true,};

As you can see I added react-native as exclusion in modulePathIgnorePatterns so Jest doesn't use that react native lib because it's present directly on projectA node_modules. I also added the same path in transformIgnorePatterns so Jest doesn't try to transform the code for that react-native dir since it's already been told to do it for the one in the projectA node_modules.

I'm not well versed in this configs so I don't know what am I doing wrong.

Can anybody help or give me a hint about my mistake or the correct way to achieve my goal? Thank you in advance.

How do I set custom drawer items to "focused" dynamically?

$
0
0

My end goal here is to give a few drawer items custom background colors depending on a few states set elsewhere. I understand that in order to give unique background colors to drawer items, I need to set up custom drawer content. However, I am having an issue in which I cannot get the custom drawer icons to know if they are in focus or not.

I originally thought that I could just do a const [bHomeFocused, setbHomeFocused] = useState(false) (etc) and setting state on onPress and then setting the focused property on that, but when a bunch more drawer items come in, I think that sounds like an unwieldy solution.

I'm sure there is a simple answer that I'm missing, as non-custom DrawerItems have this functionality inherently...

import { Drawer } from 'react-native-paper'import { createDrawerNavigator, DrawerNavigationProp, DrawerItem, DrawerContentScrollView, DrawerItemList, DrawerContentComponentProps, DrawerContentOptions } from '@react-navigation/drawer';function CustomDrawerContent(props: DrawerContentComponentProps<DrawerContentOptions>) {    return (<DrawerContentScrollView {...props}><Drawer.Section><DrawerItem                    label="Dashboard"                    labelStyle={{ color: colorTheme.normalText }}                    icon={() => <Icon name="book" type="feather" size={26} color={colorTheme.normalText} />}                    activeBackgroundColor={colorTheme.panel}                    inactiveBackgroundColor={colorTheme.cyan}                    onPress={() => {                        props.navigation.navigate('Dashboard')                    }}                /></Drawer.Section><DrawerItem                label="Home"                labelStyle={{ color: colorTheme.normalText }}                icon={() => <Icon name="home" type="feather" size={26} color={colorTheme.normalText} />}                activeBackgroundColor={colorTheme.panel}                inactiveBackgroundColor={colorTheme.red}                onPress={() => {                    props.navigation.navigate('HomeStack')                }}            /></DrawerContentScrollView>    );}export type DrawerParamList = {    Dashboard: undefined;    HomeStack: undefined;};export type DrawerProps<T extends keyof DrawerParamList> = {    navigation: DrawerNavigationProp<DrawerParamList, T>;    route: RouteProp<DrawerParamList, T>;};const AppDrawer = createDrawerNavigator<DrawerParamList>();export default function MainDrawer({ route, navigation }: TopLevelStackProps<"MainDrawer">) {    return (<AppDrawer.Navigator            drawerStyle={globalStyles.drawer}            drawerContent={                (props) => <CustomDrawerContent {...props} />            }            drawerContentOptions={{                labelStyle: { color: colorTheme.normalText },                activeBackgroundColor: colorTheme.panel,                inactiveBackgroundColor: colorTheme.background,            }}><AppDrawer.Screen                name="Dashboard"                component={Dashboard}                options={{                    unmountOnBlur: true,                }}            /><AppDrawer.Screen                name="HomeStack"                component={HomeStack}                options={{                    unmountOnBlur: true,                }}            /></AppDrawer.Navigator>    );}

Placing a marker by clicking anywhere on the mapview screen in react native

$
0
0

My problem is, im trying to make my mapView so everytime I tap on it a marker is created and the marker's latitude and longitude are sent to the console in order to send them using fetch, I found something similar here but it's made in a class and im trying to make it out of fucntion element.

Heres the code:

  constructor(props) {  super(props)  this.state = {    region: {      latitude: 24.92009056750823,       longitude: 67.1012272143364,      latitudeDelta: 0.1,      longitudeDelta: 0.1    },    markers: []  }}<MapView style={styles.map} region={this.state.region}onPress={(e) => this.setState({ markers: [...this.state.markers, { latlng: e.nativeEvent.coordinate }] })}>{    this.state.markers.map((marker, i) => (<MapView.Marker key={i} coordinate={marker.latlng} />    ))}</MapView>  

insert space in overlapping rows?

$
0
0

On my screen, I map text, along with an icon (styled as rows). This works well in iOS but the rows (including icons/text) overlap in Android.

I tried using lineHeight as suggested by other SO answers but it didn't work for me. How can I fix this?

The list is rendered in the FilterCriteriaList component.

  return (<View style={styles.container}><View style={styles.horizontalLine} />      {criteriaList.map((item: CriteriaList, index: number) => (<View key={index}><View style={styles.criteriaRow}><Icon              name={item.checked ? 'dot-circle-o' : 'circle-thin'}              color="#31C283"              size={moderateScale(20)}/><Text style={styles.text}>{item.title}</Text></View><View style={styles.horizontalLine} /></View>      ))}</View>  );};const styles = StyleSheet.create({  container: {    flex: 1,  },  criteriaRow: {    flexDirection: 'row',    paddingLeft: moderateScale(25),    alignItems: 'center',  },  horizontalLine: {    width: '100%',    height: moderateScale(1),    backgroundColor: '#f0f0f0',  },  text: {    paddingLeft: moderateScale(15),    paddingBottom: moderateScale(15),    marginBottom: moderateScale(15),    paddingTop: moderateScale(15),  },});
<View style={styles.filterCriteriaContainer}><Text style={styles.greyHeadingText}>Weitere Filter</Text><FilterCriteriaList/></View>  filterCriteriaContainer: {    paddingTop: moderateScale(35),    zIndex: 1,  },

Android:enter image description here

iOS:enter image description here

How can I type check ReactNavigation's navigation using NavigationHelpersCommon?

$
0
0

I am new to the typescript screen, so the answer may be an obvious one. I am passing ReactNavigation's navigator as a prop to a functional component and I currently type check using navigator: object, but would love to use the typescript definition from ReactNavigation, so my code doesn't complain about things like "navigation.navigate" and so forth.

I found the type definition inside @react-navigation/core/lib/typescript/src/types.d.ts; however it is not exported.

I also found this in the ReactNavigation documentation, which indicates that I may be approaching this completely at the wrong angle.

https://reactnavigation.org/docs/typescript/#annotating-usenavigation

Or maybe I should find a way to use the useNavigation hook, but that would require me to use use component that wasn't a function like I prefer.

Bottomline: How can I import the NavigationHelpersCommon declaration to type check against?

Invariant Violation: React Native w/ Typescript trying to use Material UI

$
0
0

Working in React Native, trying to use Material UI with typescript. Everything I've looked up says "Use a capital letter for your component name" and well... I've got that. I'm not sure what else this could be stemming from. I thought it might be the typescript possibly, but I uninstalled and reinstalled it all. Below are my dependencies in case I may be missing any?

dependencies:

"dependencies": {"@material-ui/core": "^4.11.0","@material-ui/icons": "^4.9.1","expo": "~38.0.9","expo-splash-screen": "^0.5.0","expo-status-bar": "^1.0.0","expo-updates": "~0.2.8","react": "~16.11.0","react-dom": "~16.11.0","react-native": "~0.62.2","react-native-gesture-handler": "~1.6.0","react-native-reanimated": "~1.9.0","react-native-screens": "~2.9.0","react-native-unimodules": "~0.10.0","react-native-web": "~0.11.7"  },"devDependencies": {"@babel/core": "~7.9.0","@types/material-ui": "^0.21.8","@types/react": "~16.9.23","@types/react-dom": "~16.9.8","@types/react-native": "~0.61.23","babel-preset-expo": "~8.2.0","jest-expo": "~38.0.0","typescript": "~3.9.5"  },"jest": {"preset": "react-native"  },

Am I missing anything in the dependencies maybe?

Trying to make a simple date/time picker component, but I can't import a material UI icon. Below is the code for the component (I'll be breaking views into sub components eventually):

import React from 'react';import Background from './components/background';import { StyleSheet, View, Text, StatusBar } from 'react-native';import CalendarTodayIcon from '@material-ui/icons/CalendarToday';export default function App() {  return (<View style={styles.container}><View style={styles.calApptComponentContainer}><View style={styles.calHeader}><Text style={{ borderColor: "green", borderWidth: 1, flex: 1 }}>            Tues, Jan 14</Text><View            style={{              borderColor: "purple",              borderWidth: 1,              flex: 1,              alignItems: "flex-end",            }}><CalendarTodayIcon /></View></View><View style={styles.calWeekdaySelector}><Text style={styles.calWeekdayItemText}>S</Text><Text style={styles.calWeekdayItemText}>M</Text><Text style={styles.calWeekdayItemText}>T</Text><Text style={styles.calWeekdayItemText}>W</Text><Text style={styles.calWeekdayItemText}>T</Text><Text style={styles.calWeekdayItemText}>F</Text><Text style={styles.calWeekdayItemText}>S</Text></View><View style={styles.calMeetingTimeSelectorContainer}><Text>CalMeetingTimeSelector</Text></View><View style={styles.calFooter}><Text>CalFooter</Text></View></View><Background /><StatusBar /></View>  );}

and then finally I get this error:

enter image description here

To make things even stranger, it works when I run expo via the web, but not on my phone or a phone emulator. Help please?

The picture shows the error on line 22 of App.tsx, that's where <CalendarTodayIcon /> is being called, because the lines aren't listed here.

React-Native Typescript, Constructor isn't assigning property

$
0
0

I have a simple TSC class in my React Native App, that has a constructor, every property is set correctly except weight lbs, it returns undefined. Could someone tell me what's going on?

Class Foo{    sets:number;    reps:number;    weight: number;    weightLbs:number;    constructor(_sets:number,_reps:number,_weight:number) {      this.sets=_sets;      this.reps=_reps;      this.weight=_weight;      this.weightLbs = _weight * 2;    }}

I am suspecting the class isn't being properly re-compiled to JS but I am not sure, it seems so weird

Typescript React Native Property 'scrollToIndex' does not exist on type 'FlatList'

$
0
0

I have a component that scrolls a React Native FlatList:

<BottomCarousel   ...   onSnapToItem={(index) => {      myList.current?.scrollToIndex({ animated: false, index });   }}/>

myList is a FlatList which is referenced with useRef:

const myList = useRef<FlatList<SomeList>>(null);

And I define the type of the list with:

type SomeList = {  id: string;  name: string;  ...

Nothing special here. It all works, but I get a TypeScript warning/error:

Property 'scrollToIndex' does not exist on type 'FlatList<SomeList>'.

Any ideas why? What am I doing wrong here?

overlap button with another view

$
0
0

I have a screen where I input some values in the input field and get search results displayed accordingly (within the <View style={styles.dropdown}>). I want that the list should overlap my ActionButton. Just like it overlaps my other input field.

I have already added zIndex and it works for the second input field but not for the button.

  return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.container}><View style={styles.searchFieldContainer}><AddressSearchInput            addressType="favouritePoint"            iconName="search"            textChangeHandler={textChangeHandler}/></View><View style={styles.dropdown}><LocationsFound            addressesFound={locations.addressesFoundList}/></View><View style={styles.fieldDescription}><Text>Standortname:</Text></View><View style={styles.searchFieldContainer}><Item style={styles.searchField}><Input style={styles.searchText}/></Item></View><View style={styles.buttonContainer}><ActionButton buttonText="Platz Speichern"/></View></View></SafeAreaView>  );};export const styles = StyleSheet.create({  searchFieldContainer: {    alignItems: 'center',    height: moderateScale(120),  },  buttonContainer: {    flexDirection: 'row',    justifyContent: 'center',    zIndex: 1,  },  fieldDescription: {    alignItems: 'center',  },  dropdown: {    position: 'absolute',    top: moderateScale(215),    zIndex: moderateScale(10),    backgroundColor: '#fff',  },  container: {    height: '100%',    backgroundColor: 'white',    width: '100%',    flex:1,  },});

scroll when the keypad is open

$
0
0

On my screen, I type in the input field and get search results accordingly. The list is rendered within a ScrollView but it still doesn't let me scroll when the keypad is open (in Android at least).

How can I fix this?

This is the component where the scroll view is rendered.

export const LocationsFound: React.FunctionComponent<LocationsFoundProps> = ({  addressesFound,}) => {  return (<>      {addressesFound.length > 0 ? (<KeyboardAwareScrollView          style={styles.searchResultsContainer}          keyboardShouldPersistTaps={'always'}          keyboardDismissMode={'on-drag'}>          {addressesFound.map((addressDetails: addressDetailsType) => {            return (<View                key={addressDetails.placeName}                style={styles.resultContainer}><Text                  style={styles.text}                  onPress={() => handleLocationSelection(addressDetails)}>                  {addressDetails.placeName}</Text></View>            );          })}</KeyboardAwareScrollView>      ) : null}</>  );};const styles = StyleSheet.create({  searchResultsContainer: {    width: moderateScale(400),    paddingHorizontal: moderateScale(50),    paddingRight: moderateScale(65),    marginTop: moderateScale(10),  },  resultContainer: {    marginTop: moderateScale(10),    borderBottomWidth: 1,    borderBottomColor: 'grey',  },  text: {    fontSize: moderateScale(15),  },});

This is the component where the LocationsFound component is called.

return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.container}><View style={styles.searchFieldContainer}><AddressSearchInput            addressType="favouritePoint"            placeholder="Ort eingeben"          /></View><View style={styles.dropdown}><LocationsFound            addressesFound={locations.addressesFoundList}          /></View></View></SafeAreaView>  );};export const styles = StyleSheet.create({  safeAreaViewContainer: {    flex: 1,  },  container: {    height: '100%',    backgroundColor: 'white',    width: '100%',    display:"flex",  flexDirection:"column",flex: 1  },  dropdown: {    position: 'absolute',    top: moderateScale(215),    zIndex: moderateScale(10),    backgroundColor: '#fff',   flex: 1  },});

enter image description here

I also tried adding

onScrollBeginDrag={Keyboard.dismiss}

but it doesn't make a difference.

unable to click on Icon in android

$
0
0

I have a screen where I will render some icons as buttons. It works in iOS but on Android, I am unable to click on the Icon. It has something to do with the overlaying Views/zIndexes. But I am unable to figure it out.

This is my list component where I render the icons.

const criteriaList = [{ id: 0, title: 'Nur Frauen', checked: false }];export const FilterCriteriaList: React.FunctionComponent = () => {  const handleChange = (index: number) => {    console.log('cccliiickckk', index); };  return (<View style={styles.container}><View style={styles.horizontalLine} />      {criteriaList.map((item: CriteriaList) => (<View style={styles.rowContainer} key={item.id}><View style={styles.criteriaRow}><Icon              style={styles.icon}              name={item.checked ? 'dot-circle-o' : 'circle-thin'}              color="#31C283"              size={moderateScale(20)}              onPress={() => handleChange(item.id)}            /><Text style={styles.text}>{item.title}</Text></View><View style={styles.horizontalLine} /></View>      ))}</View>  );};const styles = StyleSheet.create({  container: {    flex: 1,  },  rowContainer: {    //flex: 1,    paddingTop: 40,  },  criteriaRow: {    flexDirection: 'row',    paddingLeft: moderateScale(25),    alignItems: 'center',    flex: 1,    marginTop: 15,  },  horizontalLine: {    width: '100%',    height: moderateScale(1),    backgroundColor: '#f0f0f0',    marginTop: 15,  },  icon: {    paddingBottom: 40,  },  text: {    paddingLeft: moderateScale(15),    paddingBottom: moderateScale(35),    marginBottom: moderateScale(15),    paddingTop: moderateScale(15),    flex: 1,  },  button: {    backgroundColor: 'red',    flex: 1,  },});

This is the container for the above mentioned list component.

<View style={styles.filterCriteriaContainer}><Text style={styles.greyHeadingText}>Weitere Filter</Text><FilterCriteriaList/></View>...  filterCriteriaContainer: {    paddingTop: moderateScale(35),    zIndex: 1,  },

How can I fix this? I have already tried using TouchableOpacity/buttons as well but I cannot click on them either. Somehow the views are overlapping.

TSLINT Error: Property 'Component' does not exist on type 'typeof React'

$
0
0

I downloaded the [react-native-redux-typescript-boilerplate]: https://reactnativeseed.com/ . The project runs smoothly in an android emulator. However, there are loads of tslint errors especially in the JSX syntax (i.e., .tsx files). One major one is https://reactnativeseed.com/

I use webstrom as my code editor, and I crossed checked the version of typescript being used by webstrom and the project. There are the same.

These are the versions:1. Typescript - 2.6.22. react-native - 0.59.63. react - 16.2.04. react-redux - 5.0.65. @types/react - "^16.8.14"6. @types/react-native - "^0.47.7"

Is there anything else I need to check for?

I have also installed ["tslint-fix": "^0.1.3"]: https://www.npmjs.com/package/tslint-fix

ex: index.tsx

import * as React from "react";import { Item, Input, Icon, Form, Toast } from "native-base";import { Field, reduxForm } from "redux-form";import Login from "../../stories/screens/Login";const required = value => (value ? undefined : "Required");const maxLength = max => value => (value && value.length > max ? `Must be ${max} characters or less` : undefined);const maxLength15 = maxLength(15);const minLength = min => value => (value && value.length < min ? `Must be ${min} characters or more` : undefined);const minLength8 = minLength(8);const email = value =>    value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) ? "Invalid email address" : undefined;const alphaNumeric = value => (value && /[^a-zA-Z0-9 ]/i.test(value) ? "Only alphanumeric characters" : undefined);export interface Props {    navigation: any;    valid: boolean;}export interface State {}class LoginForm extends React.Component<Props, State> {    textInput: any;    renderInput({ input, meta: { touched, error } }) {        return (<Item error={error && touched}><Icon active name={input.name === "email" ? "person" : "unlock"} /><Input                    ref={c => (this.textInput = c)}                    placeholder={input.name === "email" ? "Email" : "Password"}                    secureTextEntry={input.name === "password" ? true : false}                    {...input}                /></Item>        );    }    login() {        if (this.props.valid) {            this.props.navigation.navigate("Drawer");        } else {            Toast.show({                text: "Enter Valid Username & password!",                duration: 2000,                position: "top",                textStyle: { textAlign: "center" },            });        }    }    render() {        const form = (<Form><Field name="email" component={this.renderInput} validate={[email, required]} /><Field                    name="password"                    component={this.renderInput}                    validate={[alphaNumeric, minLength8, maxLength15, required]}                /></Form>        );        return <Login loginForm={form} onLogin={() => this.login()} />;    }}const LoginContainer = reduxForm({    form: "login",})(LoginForm);export default LoginContainer;

in the above file in the render() a lot of errors are shown.some of it are:1. Property 'Component' does not exist on type 'typeof React'.2. JSX element type 'Item' is not a constructor function for JSX elements. Property 'render' is missing in type 'Item'.and many more similar one.

Lerna with Yarn, TypeScript and React Native: Cannot find module '@project/common' or its corresponding type declarations.ts(2307)

$
0
0

The project uses Yarn, React Native, Lerna and Typescript. It is structured as a monorepo

Here is the structure:

project|- packages   | - mobile       | - src       | - packages.json       | - tsconfig.json   | - cloud-functions       | - src       | - packages.json       | - tsconfig.json   | - common1       | - lib       | - src       | - packages.json       | - tsconfig.json   | - common2       | - lib       | - src       | - packages.json       | - tsconfig.json| - packages.json| - tsconfig.json| - lerna.json

lerna.json looks like this:

{"packages": ["packages/*"  ],"npmClient": "yarn","version": "0.0.7",}

The root packages.json looks like this:

{"name": "project","private": true,"scripts": {    ...  },"devDependencies": {"@types/node": "^14.0.27","lerna": "^3.22.1","ts-node": "^8.10.2","typescript": "^3.9.7"  }}

The root tsconfig.json looks like this:

{"compilerOptions": {"noImplicitAny": true,"noUnusedLocals": true,"removeComments": true,"noLib": false,"emitDecoratorMetadata": true,"experimentalDecorators": true,"sourceMap": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"resolveJsonModule": true,"baseUrl": "./","paths": {"@project/common1": ["packages/common1/lib"],"@project/common2": ["packages/common2/lib"],"@project/mobile": ["packages/mobile/src"],"@project/cloud-functions": ["packages/cloud-functions/src"],    }  },"exclude": ["node_modules", "**/*.spec.ts", "**/__tests__/*", "babel.config.js", "metro.config.js", "jest.config.js"]}

The typical packages/common/packages.json looks like this:

{"name": "@project/common1","version": "0.0.7","main": "lib/index.js","types": "lib/index.d.ts","files": ["lib/**/*"  ],"private": true,"devDependencies": {"@project/common2": "latest", //for common1 only"@types/node": "^14.0.27","ts-node": "^8.10.2","typescript": "^3.9.7"  },"dependencies": {    ...  }}

The typical packages/common/tsconfig.json looks like this:

{"extends": "../../tsconfig.json","compilerOptions": {"module": "commonjs","outDir": "lib","strict": true,"target": "es6"  },"compileOnSave": true,"include": ["src"]}

The React Native file packages/mobile/packages.json looks like this:

{"name": "@project/mobile","version": "0.0.7","private": true,"dependencies": {"@project/common1": "latest","@project/common2": "latest",        ...    },"devDependencies": {        ..."ts-node": "^8.10.2","typescript": "^3.8.3"    },}

I first ran into:

lerna ERR! yarn install --mutex network:42424 --non-interactive stderr:warning Waiting for the other yarn instance to finish (19560)warning Waiting for the other yarn instance to finish (21568)error An unexpected error occurred: "https://registry.yarnpkg.com/@project%2fcommon1: Not found".

Obviously Yarn is trying to pull the dependencies from its packages registery. This fails.

Then I tried to remove the references to @project/common1 and @project/common2 in the dependencies of the packages.

In the source, VS Code underline the imports in red and prints:

Cannot find module '@project/common1' or its corresponding type declarations.ts(2307)

I also tried to use Yarn Workspace, yet I ran into modules hoisting issues with React Native. I did not want create a list of all possibly incompatible package, since it seems to be difficult to maintain.

"workspaces": {"nohoist": ["react-native", "react-native/**", "@react-native-community/checkbox", "@react-navigation/native"]}

Is there a simple solution ?

Or is it simpler for this use case to abandon Lerna and use GitHub based common repositories?

How to access data from FlatList in to parent component to be used in a function

$
0
0

i'm trying to access the code and name value from within my child component which is a flatlist and access the select data in the parent component:

My flatList is as follows & it house a child component on which it will render items to. But however i get undefind or maybe i've used the wrong approach

const CustomerView = ({ code, name, email, balance, buttonPress }: any) => {  return (<View style={styles.body}><TouchableOpacity onPress={buttonPress}><Text>Code: {code}</Text><Text>Name: {name}</Text><Text>E-Mail: {email}</Text><Text>Balance: {balance}</Text></TouchableOpacity></View>  );};

And below is my flatList component which will render the above componet when data gets passed through

const CustomerFlatList = ({  customerData,  onPressSelectCustomer,}: any) => {  return (<View style={styles.body}><FlatList        data={customerData}        keyExtractor={(customerData) => customerData.code.toString()}        //I need to access code and name in the parent component        renderItem={({ item: { code, name, email, balance } }) => {          return (<View><CustomerView                code={code}                name={name}                email={email}                balance={balance}                buttonPress={onPressSelectCustomer}              /></View>          );        }}      /></View>  );};

And my home component which is supposed to get code, name passed through in order to trigger an event with there data being passed through

const SelectCustomerScreen = ({navigation}) => {  const customers = useSelector((state: RootStateOrAny) => state.customers);  const getCustomerDetails = (code, name) => {      //navigation.navigate("orderScreen");      console.log(code, name)  }  return (<View style={{ flex: 1 }}><CustomerFlatList        customerData={customers}        doc_type={documentType}        invoiceScreen={invoiceScreen}        quotationScreen={quotationScreen}        onPressSelectCustomer={getCustomerDetails}      /></View>  );};
Viewing all 6214 articles
Browse latest View live


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