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

TypeScript + React Native SectionList

$
0
0

No overload matches this call.Overload 1 of 2, '(props: Readonly<SectionListProps>): SectionList', gave the following error.Property 'sections' is missing in type '{ children: any[]; }' but required in type 'Readonly<SectionListProps>'.Overload 2 of 2, '(props: SectionListProps, context?: any): SectionList', gave the following error.Property 'sections' is missing in type '{ children: any[]; }' but required in type 'Readonly<SectionListProps>'.

<SafeAreaView><SectionList>      ListHeaderComponent={() => (<><BarApresentation bar={bar}/><CategoryList/><HightlightList/></>      )}      sections={organizedDishes}      keyExtractor={(item: { id: number; }) => item.id}      renderItem={({ item }) => (<View><Text>            {item.name}</Text></View>      )}      renderSectionHeader={({ sections }) => (<Text>{Title}</Text>      )}</SectionList></SafeAreaView>```

How to call one saga at the end of another redux-saga like a async await in redux-thunk

$
0
0

I have two sagas, one gets the cities, the other is the weather forecast for these cities (according to ID specialists), how can I make it so that the second saga is processed at the end of the first?method in which a call my sagas:

async componentDidMount() {    this.props.navigation.setOptions(this.navigationOptions);    //sagas call        await this.props.fetchCities();        await this.fetchForecastsHandler(this.props.userCities);  } ...some code fetchForecastsHandler(cities: ICIty[]) {    const ids = cities.map((el) => el.id);    this.props.fetchForecasts(ids);  }``...some code   render(){...}

My index.ts saga

export function* mySaga() {    yield takeEvery(types.FETCH_USERS_CITIES, fetchUserCitiesWorker);    yield takeEvery(types.REMOVE_CITY, removeUserCitiesWorker);    yield takeEvery(types.SEARCH_CITY, searchUserCitiesWorker);    yield takeEvery(types.FETCH_FORECAST, fetchForecastWorker);    yield takeEvery(types.ADD_NOTIFICATION, addNotificationWorker);    yield takeEvery(types.EDIT_NOTIFICATION, editNotificationWorker);    yield takeEvery(types.DELETE_NOTIFICATION, deleteNotificationsWorker);    yield takeEvery(types.FETCH_NOTIFICATION, fetchNotificationsWorker);}**FeychCityWorker saga:** export function* fetchUserCitiesWorker(callback?:any) {    try {        yield put({ type: types.FETCH_USERS_CITIES_START });        //const user = yield call(Api.fetchUser, action.payload.userId);        yield delay(2000,true)        yield put({ type: types.FETCH_USERS_CITIES_SUCCESS, payload: userCities });        console.log("fetchUserCitiesWorker worked sucess")        //callback?callback():null    } catch (e) {        yield put({ type: types.FETCH_USERS_CITIES_ERROR, error: e.message });    }}**also storage settings just in case:**const sagaMiddleware = createSagaMiddleware()export const store = createStore(  reducer,  applyMiddleware(sagaMiddleware))export const action = (type:string) => store.dispatch({type})sagaMiddleware.run(mySaga)

How to get blob of an locally saved image?

$
0
0

I am using “expo”: “38.0.8” to develop iOS and Android application.Currently I am trying to upload blob of an image to company server, sending it with custom Axios Post method, packing blob as one part of data.

I get the image from the device locally:

const imagePicker = camera ? ImagePicker.launchCameraAsync : ImagePicker.launchImageLibraryAsync;let image = await imagePicker({   mediaTypes: ImagePicker.MediaTypeOptions.Images,   allowsEditing: true,   quality: 1});The problem for me is to create blob and checking if it was created.I have tried:    fetch(image.uri)      .then(response =>        response.blob()        .then(blob => {           console.log(blob)        })     );and:    const blob = await new Promise((resolve, reject) => {      const xhr = new XMLHttpRequest();      xhr.onload = function() {        resolve(xhr.response);      };      xhr.onerror = function() {        reject(new TypeError('Network request failed'));      };      xhr.responseType = 'blob';      //@ts-ignore      xhr.open('GET', image.uri, true);      xhr.send(null);        }).then(blob => {           console.log(blob)           }    );

But both of them return me error: value.hasOwnProperty is not a function.The weird thing is that if try to display blob.size it works.Am I doing something wrong, is there a way to display blob or is blob not supported?

Thanks for any advice

TypeError: Object prototype may only be an Object or null: undefined at setPrototypeOf () in react native

$
0
0
//Super.tsxclass Super extends React.Component {    someMethod = () => {    }}export { Super };//ClassA.tsximport {Super} from '../Super';class ChildA extends Super {    componentDidMount() {        this.someMethod();    }}//ClassB.tsximport {Super} from '../Super';class ChildB extends Super {    componentDidMount() {        this.someMethod();    }}//ClassC.tsximport {Super} from '../Super';class ChildC extends Super {    componentDidMount() {        this.someMethod();    }}//ClassA.test.tsximport { ClassA } from '../ClassA'describe('ClassA', () => {    let wrapper: any;    let instance: any;    const props = createTestProps({});    beforeEach(() => {        wrapper = shallow<ClassA>(<ClassA {...props} />);        instance = wrapper.instance()    });})

Functionally it is working fine, but when i ran the jest unit test cases i am getting TypeError: Object prototype may only be an Object or null: undefinedat setPrototypeOf () error. Please suggest any solution.Thanks

decrease distance between bottomBorder and text

$
0
0

As an underline, I have added borderBottom to a view that is wrapped around my text element. However, the bottom is a bit lower than how I want it to be. Is there any way I can reduce the distance?

<View            style={[              styles.textContainer,              selected === index ? styles.selectedTab : null,            ]}><Text style={styles.tabText}>{item.text}</Text></View>
  selectedTab: {    borderBottomWidth: 3,    borderBottomColor: 'red',  }

Codesandbox:You'll see the underline when you click on one of the text items.https://snack.expo.io/@nhammad/shallow-watermelon

Property doesn't exist on type 'object' in React Native with TypeScript

$
0
0

I'm very new to React Native and TypeScript so forgive me if the the question is trivial.

In my application I have a screen to which I'm navigating with React-Navigation I'm also passing a callback function through the navigation.

navigation.navigate('BluredSuccess', {blurredSuccessCallback})

I show the BlurredScreen for 2 secs and then I close using navigation.pop and call the callback function like this:

import { NavigationScreenProp } from 'react-navigation';import { Route } from '@react-navigation/native';interface Props {    navigation?: NavigationScreenProp,    route: Route<any>}const LoginOtpSuccess : React.FC<Props> = ({navigation, route: {params}}) => {    React.useEffect(() => { setTimeout(() => {        navigation.pop()        params.blurredSuccessCallback() // here I see an error.    }, 2000) })    return (<View style={styles.container}><BlurView                style={styles.absolute}                blurType="light"                blurAmount={40}                reducedTransparencyFallbackColor="white"            /><Image source={require('../../../assets/otp_success.png')} style={{width:90, height:90}}></Image></View>    )}

Now the code works in general but I keep seeing an error on my callback method stating:

Property 'blurredSuccessCallback' does not exist on type 'object'. 

I also see Object is possibly 'undefined'. on the params variable.

How can I fix this error? What should be the correct types of navigation and route in my Props interface I don't think using any is the correct way.

Cross-platform React app (React native and React App) : React Native Video doesn't work

$
0
0

I try to code a cross-platform app using React. I'm using React.js for web app and React Native for Android devices, IOS devices, ...

Inside my app, I want to insert a video and for my web app it works well but when I try to run my app on Android device, I get the following error :

Failed building JavaScript bundle.The package at "node_modules/imsc/node_modules/sax/lib/sax.js" attempted to import the Node standard library module "stream". It failed because the native React runtime does not include the Node standard library. Read more at https://docs.expo.io/workflow/using-libraries/#using-third-party-libraries

I installed react-native-stream but nothing changes.Here is my Native code for the Video component :

import React from 'react';import {View} from "react-native"import Video from 'react-native-video';export const VideoComponent: React.FC= ( ) => {    return(<View><Video source="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" /></View>    )}

I'm using expo for my project and I install dependencies with yarn.

Thank for your help,

circle outline for fontAwesome icons in react native

$
0
0

I want to use the fontAwesome + icon such that it is in the middle of a circle. I want to use it as one icon item. I read that we can use it along with the circle icon and place it inside that but I couldn't make it work.

import IconFA from 'react-native-vector-icons/FontAwesome';<IconFA         name="plus"         size={moderateScale(30)}         color="black"         style={styles.thumbnail}         />        {/* <IconFA        name="circle-thin"        size={moderateScale(67)}        color="white"      /> */}  thumbnail: {    height: 68,    width: 68,    position: 'relative',  },

Alternatively, I read about 'stacked' font awesome icons but couldn't understand how to use it in react native.

Reference: https://jsfiddle.net/1d7fvLy5/1/

Snack Expo:

https://snack.expo.io/9Ild0Q1zG

I want to make something like this:

enter image description here

I am also open to using a <Thumbnail> if I find a similar icon's link but I couldn't find any such free icon online.


Stuck with react native redash library

$
0
0

I get stuck with react-native-redash library when coding (Instagram Pinch-to-Zoom). I can not use Vector (or vec) and onGestureEvent from react-native-redash such as in this Video. Because there is no implementation for them (vec just have "create function" and does not have "set function")

Does anybody know what problem is? I have used Typescript for my project. And I have read v1 Users notice in redash docs but don't know which circumstance to apply it. Thank in advance.

Library I used in my project:

"react-native-reanimated": "~1.7.0"

"react-native-redash": "^15.6.0"

"react-native-gesture-handler": "~1.6.0"

"react-native": "0.61.4"

TypeError: navigation.navigate is not a function

$
0
0
import React from 'react';import {Button, View, Text} from 'react-native';const RegistrationScreen = (navigation: any) => {  return (<View><Text>My Registration Page</Text><Button        title="Go Back"        onPress={() => navigation.navigate('HomeScreen')}></Button></View>  );};export default RegistrationScreen;

I am getting the error, when i use .tsx as extenstion of the file. ex: - RegistrationScreen.tsx, and then got the error//TypeError: navigation.navigate is not a function. (In 'navigation.navigate('HomeScreen')', 'navigation.navigate' is undefined) //

Full screen background image on HomeScreen in React Native app iphone 11

$
0
0

I'm currently trying to set a full background image on my login view on iphone 11

     const Background = styled.ImageBackground`      padding:20px;      justify-content:center;      width:100%;      height:100%;      `      const styles = StyleSheet.create({            imageContainer: {              flex: 1,              alignItems: 'stretch'            },            image: {              flex: 1            }          });        return <SafeAreaView style={styles.imageContainer}><Background style={styles.image} source={require('../../assets/images/background-cover.jpg')}><CoverLogo width={100} height={100} color={Colors.White} /><Introduction loop={false}><TextHeading text={`TestHeader`} /></Background></SafeAreaView>

Currently what gets outputted:

enter image description here

I want the background to take over the white space. This issue seems to only occur in phone 11s

React Navigation v5 how to navigate between tabs with typescript

$
0
0

Here is my navigator. I have a bottomTab with 3 stack navigators as screens 'Home''Profile''Discover', and main root stack navigator with bottom tab navigator and few modal screens. I can not understand how to do Type checking with TypeScript right from guide in docs. Can someone explain me what am i doing wrong. For right now if i want to navigate from tab Home to tab Profile i can see only to 'Home' and all modal screens and to tabNavigator itself but not to tabs of my tabNavigator:

enter image description here

my code of mainNavigator:

export type TabParamList = {  Home: undefined;  Discover: undefined;  Profile: undefined;}export type MainStackParamList = {  TabNavigator: undefined;  ModalStreamsPlayer: { streamsQualitys: ParsedStream[], stream: Stream} | undefined;  ModalWebBrowser: { url: string, title: string } | undefined;  ModalVideoPlayer: { video: Video } | undefined;}export type HomeStackParamList = {  Home: undefined;}export type DiscoverStackParamList = {  Discover: undefined;}export type ProfileStackParamList = {  Profile: undefined;}const Tab = createBottomTabNavigator<TabParamList>();const RootStack = createStackNavigator<MainStackParamList>();const HomeStack = createStackNavigator<HomeStackParamList>();const DiscoverStack = createStackNavigator<DiscoverStackParamList>();const ProfileStack = createStackNavigator<ProfileStackParamList>();const screenOptions = ({ route }): StackNavigationOptions => {  return {    title: route.name,    headerTitleStyle: {      fontFamily: 'ProximaNova-Semibold',      fontSize: 18,      textTransform: 'uppercase',      lineHeight: 22,      color: '#D6FFFD'    },    headerStyle: {      backgroundColor: '#133740',      elevation: 0,      shadowOpacity: 0,      borderBottomWidth: 0    },    headerTintColor: '#D6FFFD',    headerTitleAlign: 'center',  }}const TabHomeStack = () => {  return (<HomeStack.Navigator><HomeStack.Screen        name='Home'        component={HomeScreen}        options={screenOptions}      /></HomeStack.Navigator>  );};const TabDiscoverStack = () => {  return (<DiscoverStack.Navigator><DiscoverStack.Screen        name='Discover'        component={DiscoverScreen}        options={screenOptions}      /></DiscoverStack.Navigator>  );}const TabProfileStack = () => {  return (<ProfileStack.Navigator><ProfileStack.Screen        name='Profile'        component={ProfileScreen}        options={screenOptions}      /></ProfileStack.Navigator>  )}const TabNavigator = () => {  return (<Tab.Navigator      tabBarOptions={{        showLabel: false,        // activeTintColor: '#2F80ED',        // inactiveTintColor: '#999999',        style: {          backgroundColor: '#133740',          height: Platform.OS === 'ios' ? 94 : 60,          borderTopWidth: 0        }      }}><Tab.Screen        name='Home'        component={TabHomeStack}        options={{ tabBarIcon: ({color, focused, size}) => (<Image          source={ focused ? images.tabBarIconHomeActive : images.tabBarIconHomeNormal }           />        )}}      /><Tab.Screen        name='Discover'        component={TabDiscoverStack}        options={{ tabBarIcon: ({color, focused, size}) => (<Image          source={ focused ? images.tabBarIconDiscoverActive : images.tabBarIconDiscoverNormal }           />        )}}      /><Tab.Screen        name='Profile'        component={TabProfileStack}        options={{ tabBarIcon: ({color, focused, size}) => (<Image          source={ focused ? images.tabBarIconProfileActive : images.tabBarIconProfileNormal }           />        )}}      /></Tab.Navigator>  );};const RootStackNavigator = () => {  return (<RootStack.Navigator mode='modal'><RootStack.Screen        name='TabNavigator'        component={TabNavigator}        options={{ headerShown: false }}      /><RootStack.Screen        name='ModalStreamsPlayer'        component={StreamsPlayer}        options={{ headerShown: false }}      /><RootStack.Screen      name='ModalWebBrowser'      component={WebScreen}      options={{ headerShown: false }}      /><RootStack.Screen        name='ModalVideoPlayer'        component={YoutubePlayer}        options={{ headerShown: false }}      /></RootStack.Navigator>  );}export default RootStackNavigator;

Home screen from Home tab:

type HomeScreenNavigationProp = CompositeNavigationProp<  BottomTabNavigationProp<HomeStackParamList, 'Home'>,  StackNavigationProp<MainStackParamList>>;type HomeScreenRouteProp = RouteProp<  HomeStackParamList, 'Home'>;export type HomeProps = {  navigation: HomeScreenNavigationProp;  route: HomeScreenRouteProp;};export default class HomeScreen extends React.Component<HomeProps> {  render() {    return (<View style={styles.container}><ScrollView style={styles.scrollView}><View style={{ paddingBottom: 24 }}><StreamsScreen navigation={this.props.navigation} /><View style={styles.separator}></View><NewsScreen navigation={this.props.navigation} /><View style={styles.separator}></View><VideosScreen navigation={this.props.navigation} /><View style={styles.separator}></View></View></ScrollView></View>    );  }}

Unhandled promise rejection: TypeError: null is not an object (evaluating camera.pictureSize)

$
0
0

I am creating a react-native app to use the expo-camera module.

So I declared a camera variable as

let camera: any = null;

I am passing a reference to this from the return as:

<Camera style = {{flex: 1, opacity: camOpacity}}          type = {state.type}          ratio = "2:1"          ref = {async (ref) => (camera = ref)}>

But when I run the app, it starts normally but on trying to take a picture it gives the error:

[Unhandled promise rejection: TypeError: null is not an object (evaluating 'camera.pictureSize')]

This error is occuring from :

console.log(camera.pictureSize);

But it is also happening at:

console.log(" --> Taking image");    const opts = {       skipProcessing: true,       exif: false,       quality: 0    };    let photo = await camera.takePictureAsync(opts);

from the camera.takePictureAsync(opts) part when I am commenting out the console.log(camera.pictureSize);

For some reason the reference isn't getting detected maybe.

My package.json is:

"dependencies": {"expo": "~39.0.2","expo-2d-context": "0.0.2","expo-asset": "~8.2.0","expo-camera": "~9.0.0","expo-gl": "~9.1.1","expo-image-manipulator": "~8.3.0","expo-permissions": "~9.3.0","react": "16.13.1","react-dom": "16.13.1","react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz","react-native-web": "~0.13.12","react-native-screens": "~2.10.1","react-native-svg": "~12.1.0","mem": "^8.0.0","@unimodules/core": "~5.5.0"  }

I read there were some such errors in the current expo-camera release, but even if I downgrade the packages and dependencies it is still being persistent.

Any help would be really appreciated.

how to type event in react native with defaultPrevented?

$
0
0

i am getting an event object from react navigation with its emit function. e.g.:

  const event = navigation.emit({                type: "tabPress",                target: route.key,                canPreventDefault: true,              });

the event type from above is like this: const event: EventArg<"tabPress", any, any>but i get an error with defaultPrevented prop. e.g.:

//Property 'defaultPrevented' does not exist on type 'EventArg<"tabPress", any, any>'. if (!event.defaultPrevented) { 

i have searched and failed to find a solution, i just don't wanna use any.

react-native bundle script throwing syntax error on typescript module react-navigation

$
0
0

When running a build using the react-native bundle script an error is thrown on react-navigation modules referring to typescript.

I am running the following script to build assets into a specific folder:

react-native bundle --reset-cache --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

The following error is

error SyntaxError: /Users/sachinkaria/Desktop/chemistri/qem-native-test-build/node_modules/@react-navigation/stack/src/index.tsx: Unexpected token (51:12)  49 |  * Types  50 |  */> 51 | export type {     |             ^  52 |   StackNavigationOptions,  53 |   StackNavigationProp,  54 |   StackScreenProps,. Run CLI with --verbose flag for more details.SyntaxError: /Users/sachinkaria/Desktop/chemistri/qem-native-test-build/node_modules/@react-navigation/stack/src/index.tsx: Unexpected token (51:12)  49 |  * Types  50 |  */> 51 | export type {     |             ^  52 |   StackNavigationOptions,  53 |   StackNavigationProp,  54 |   StackScreenProps,    at Object.raise (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:6400:17)    at Object.unexpected (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:7728:16)    at Object.parseIdentifierName (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:9624:18)    at Object.parseIdentifier (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:9598:23)    at Object.tsParseTypeAliasDeclaration (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:4793:20)    at Object.tsParseDeclaration (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:5111:23)    at Object.tsTryParseExportDeclaration (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:5020:17)    at Object.parseExportDeclaration (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:5497:26)    at Object.maybeParseExportDeclaration (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:11070:31)    at Object.parseExport (/Users/sachinkaria/.config/yarn/global/node_modules/@babel/parser/lib/index.js:10999:29)

My package.json is as follows:

{"name": "Example","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint .","update:pods": "cd ios && pod install --repo-update && cd ..","postinstall": "yarn run update:pods"  },"dependencies": {"@expo/react-native-action-sheet": "^3.8.0","@notifee/react-native": "^0.9.1","@ptomasroos/react-native-multi-slider": "^2.2.2","@react-native-community/async-storage": "^1.11.0","@react-native-community/checkbox": "^0.4.2","@react-native-community/clipboard": "^1.2.3","@react-native-community/datetimepicker": "^2.6.1","@react-native-community/image-editor": "^2.3.0","@react-native-community/masked-view": "^0.1.10","@react-native-community/netinfo": "^5.9.5","@react-native-community/slider": "^3.0.3","@react-native-community/toolbar-android": "0.1.0-rc.2","@react-native-community/viewpager": "^4.1.3","@react-native-firebase/app": "^8.4.1","@react-native-firebase/auth": "^8.0.9","@react-native-firebase/firestore": "^7.2.3","@react-native-firebase/messaging": "^7.2.1","@react-native-firebase/remote-config": "^9.0.2","@react-native-firebase/storage": "^7.1.7","@react-navigation/bottom-tabs": "^5.6.1","@react-navigation/native": "^5.2.6","@react-navigation/stack": "^5.3.1","@storybook/react-native": "^5.3.19","add": "^2.0.6","apisauce": "^1.1.1","base-64": "^0.1.0","compare-versions": "^3.6.0","expo-asset": "^8.1.7","expo-av": "^8.2.1","expo-constants": "^9.1.1","expo-file-system": "^9.0.1","expo-font": "^8.2.1","expo-image-manipulator": "^8.2.1","expo-image-picker": "^8.3.0","expo-location": "^8.2.1","expo-permissions": "^9.0.1","formik": "^2.1.4","i": "^0.3.6","lodash": "^4.17.15","moment": "^2.27.0","native-base": "^2.13.12","ngeohash": "^0.6.3","npm": "^6.14.5","prop-types": "^15.7.2","react": "16.11.0","react-native": "0.62.2","react-native-animatable": "^1.3.3","react-native-calendars": "^1.300.0","react-native-datepicker": "^1.7.2","react-native-device-info": "^6.0.0","react-native-dotenv": "^0.2.0","react-native-easy-grid": "^0.2.2","react-native-fbsdk": "^2.0.0","react-native-geocoding": "^0.4.0","react-native-gesture-handler": "^1.6.1","react-native-gifted-chat": "^0.16.3","react-native-keyboard-aware-scroll-view": "^0.9.1","react-native-maps": "^0.27.1","react-native-mixpanel": "^1.2.0","react-native-modal": "^11.5.6","react-native-permissions": "^2.1.5","react-native-reanimated": "^1.9.0","react-native-safe-area-context": "^0.7.3","react-native-screens": "^2.9.0","react-native-snap-carousel": "^3.9.1","react-native-splash-screen": "^3.2.0","react-native-svg": "^12.1.0","react-native-swiper": "^1.6.0","react-native-unimodules": "^0.10.1","react-native-vector-icons": "^6.6.0","react-native-view-overflow": "^0.0.5","yup": "^0.29.1"  },"devDependencies": {"@babel/core": "7.9.6","@babel/runtime": "7.9.6","@react-native-community/eslint-config": "^0.0.5","babel-jest": "^24.9.0","eslint": "^6.8.0","jest": "^24.9.0","metro-react-native-babel-preset": "^0.58.0","react-test-renderer": "16.11.0"  },"jest": {"preset": "react-native"  }}

I have tried the following:

  • Removing yarn.lock and node_modules
  • Cleaning cache with yarn cache clean
  • Gradle clean with cd android ./gradlew clean
  • Reinstalling modules
  • react-native bundle --reset-cache --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

However, this error is persisting. Any ideas?


undefined is not an object (evaluating 'h.ViewPropTypes.style') Evaluating native-base.js

$
0
0

I am unable to import Native-Base in snack expo. I checked this a few Days back too but the issued is still existing. I cannot figure out the issue. Does it have something to do with the version?

Snack Expo Link: https://snack.expo.io/@nhammad/curious-bubblegum

Package.json:

{"dependencies": {"react-native-paper": "3.6.0","react-native-size-matters": "0.3.1","react-native-vector-icons": "7.1.0","react-native-vector-icons/FontAwesome": "7.1.0","native-base": "2.13.14"  }}

Cannot read property of undefined in react navigation native with typescript

$
0
0

I'm building a react native app and I'm having trouble passing props to another screen using react-navigation/native.

Navigation set up

export type RootStackParamList = {  Home: HomeProps,  LoginDemo: undefined,  Login: undefined};const Stack = createStackNavigator<RootStackParamList>();const store = configureStore();export const Navigation: React.FC = () => {  return (<Provider store={store}><NavigationContainer><Stack.Navigator><Stack.Screen name="LoginDemo" component={LoginDemo} /><Stack.Screen name="Home" component={Home}/><Stack.Screen name="Login" component={LoginScreen} /></Stack.Navigator></NavigationContainer></Provider>  );};

Code that does the screen switching

React.useEffect(() => {    if (patrolUnits.completed) {      if (patrolUnits.error !== null)        showAlert("error", patrolUnits.error.toString());      else        navigation.replace('Home', {patrolUnitId: patrolUnits.data[0].id});    }  }, [patrolUnits.completed]);

The screen that I am switching to

export const Home: React.FC<RouteProp<RootStackParamList, "Home">> = routeProps => {    const props = routeProps.params;    const { patrolUnitId } = props;    return (<View><Text>{patrolUnitId.toString()}</Text></View>)};

And the props that should be passed

export type HomeProps = {    patrolUnitId: number;}

Can anyone tell me what I'm doing wrong. I've been trying to figure this out for hours. I've tried googling but almost everything that's recommended for me is for regular react, not react native.

move textInput element to a separate component

$
0
0

I have a screen where I use this :

const [searchText, setSearchText] = useState('');<Item rounded style={styles.inputItem}><Icon              name="search"              size={moderateScale(18)}              color="#bdbdbd"              style={styles.icon}            /><Input              autoFocus={true}              autoCapitalize="none"              style={styles.inputField}              placeholder="Friend Search"              keyboardType="default"              onChangeText={(text: string) => {                setSearchText(text);              }}            /></Item>

Instead of using the Input element on my current screen, I want to turn it into a reusable component. Something like this:

type SearchInputProps = {  handleChange?: any;};export const SearchInput: React.FunctionComponent<SearchInputProps> = (handleChange) => {  return (<Item rounded style={styles.inputItem}><Icon name='search' size={moderateScale(18)} color="#bdbdbd" style={styles.icon}/><Input        autoFocus={true}        autoCapitalize="none"        style={styles.inputField}        placeholder="Friend Search"        onChangeText={()=>handleChange}      /></Item>  );};

However, I am unable to figure out how to make the onChangeText work such that the const [searchText, setSearchText] = useState(''); value from the main screen can be set over there. Is it even possible?

I tried to create a snack expo here but I am unable to install native base https://snack.expo.io/@nhammad/curious-bubblegum

Edit:Managed to resolve the type error but still don't know how to pass setSearchText while calling the component.

type SearchInputProps = React.PropsWithRef<{  handleChange?: any;}>;export const FieldInput = React.forwardRef<Input, SearchInputProps>(  ({ handleChange }) => {    return (<Item rounded style={styles.inputItem}><Icon          name="search"          size={moderateScale(18)}          color="#bdbdbd"          style={styles.icon}        /><Input          autoFocus={true}          autoCapitalize="none"          style={styles.inputField}          placeholder="Friend Search"          keyboardType="default"          onChangeText={handleChange}        /></Item>    );  },);

How to pass additional parameters to onChange function in React

$
0
0

So, I've faced this problem: I have this type of Element here, obviously there's event when changing the input, is it possible to pass params like this and access event as well? if so, how could I do it?

// this function accepts two other params index, stringValuefunction onChange(index ,stringValue) {    console.log(event.target.value);    console.log("index?: " + index +" and value" + stringValue)}//this input is in Child Componentconst index = 69;const someRandomValue='iamstring';<input defaultValue={name} onChange={onChange(index,iamstring)} />

TypeError: seamless immutable _1.default is not a function - React native jest unit testing (Typescript)

$
0
0

I am trying jest unit testing for typescript based react native project.Now I am stuck on one issue when do npm test. Error mentioned below

● Test suite failed to run

TypeError: seamless_immutable_1.default is not a function  34 |   35 | > 36 | export const INITIAL_STATE: ImmutableAppReducerState = Immutable({     |                                                                 ^  37 |   activeTab: 0,  38 |   showTab: false,  39 |   tabName: "",

My actual code was follows

import Immutable from "seamless-immutable";

export interface AppReducerState {  activeTab?: number | undefined;  showTab?: boolean | undefined;  tabName?: string | undefined;  isDrawerOpen: boolean;  retryAction: AnyAction[];}/* ------------- Initial State ------------- */type ImmutableAppReducerState = Immutable.Immutable<AppReducerState>export const INITIAL_STATE: ImmutableAppReducerState = Immutable({  activeTab: 0,  showTab: false,  tabName: "",  isDrawerOpen: false,  retryAction: [],});
Viewing all 6214 articles
Browse latest View live


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