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

Adding type for useRef on ScrollView react-native

$
0
0

Looking to create a ref to a ScrollView component like so: const ref = useRef<ScrollView>(null); (or something to this effect) essentially I need access to the flashScrollIndicators method like this:

<ScrollView  ref={ref}  onContentSizeChange={() => ref?.current?.flashScrollIndicators()}>  {children}</ScrollView>

The code does work in my app however typescripts definitions for ScrollView doesn't seem to include flashScrollIndicators?I'm getting Property 'flashScrollIndicators' does not exist on type 'ScrollView'.ts(2339) looking through the types I can see SectionList and Flatlist so unsure if this is an bug with the definitions or just me not using it properly.


React Native - Typescript issue

$
0
0

After a transaction I did, I started getting an error like this. How can I solve the problem?

I wrote the code in React Native as typescript

The file supporting useScrollHandler.ts in the lib folder in the react-native-dash folder in the node-modules file seems to have been deleted.

enter image description here

import React, { useRef } from "react";import { View, StyleSheet, Dimensions, Image } from "react-native";import { interpolateColor, useScrollHandler } from "react-native-redash";import Animated, { multiply, divide } from "react-native-reanimated";import Slide, {SLIDE_HEIGHT, BORDER_RADIUS} from './Slide';import Subslide from "./Subslide";import Dot from "./Dot";const { width } = Dimensions.get("window");const styles = StyleSheet.create({    container: {        flex: 1,        backgroundColor: "white",    },     underlay: {        ...StyleSheet.absoluteFillObject,        alignItems: "center",        justifyContent: "flex-end",    },    slider: {        height: SLIDE_HEIGHT,        borderBottomRightRadius: BORDER_RADIUS,    },    footer: {        flex: 1,    },    footerContent: {        flex: 1,        backgroundColor: "white",         borderBottomLeftRadius: BORDER_RADIUS,    },    pagination: {         ...StyleSheet.absoluteFillObject,            height: BORDER_RADIUS,            flexDirection: "row",            justifyContent: "center",            alignItems: "center",    },});const slides = [    {         title: "Giyim",         subtitle: "Bayan Giyim",         description: "Bayan giyimde en iyi markalar",         color: "#BFEAF5",        picture: {            src: require("../images/1.jpg"),            width: 2513,            height: 3583,        },    },    {         title: "Kozmetik",         subtitle: "Parfüm",         description: "Parfümde en iyi markalar",         color: "#BEECC4",        picture: {            src: require("../images/2.jpg"),            width: 2791,            height: 3744,        },    },    {         title: "Aksesuar",         subtitle: "Takı",         description: "Aksesuar çeşitleri",         color: "#FFE4D9",        picture: {          src: require("../images/3.jpg"),          width: 2738,          heigth: 3244,          },    },    {         title: "Butik",         subtitle: "Mağazalar",         description: "Yüzlerce mağaza seçeneği",         color: "#FFDDDD",        picture: {            src: require("../images/4.jpg"),            width: 1757,            height: 2551,        },    },];const Onboarding = () => {    const scroll = useRef <Animated.ScrollView>(null);    const {scrollHandler, x} = useScrollHandler ();    const backgroundColor = interpolateColor (x, {        inputRange: slides.map((_, i) => i * width),        outputRange: slides.map((slide) => slide.color),    });    return (<View style={styles.container}><Animated.View style={[styles.slider, { backgroundColor }]}>            {slides.map(({ picture }, index) => {                return (                    <Animated.View style={styles.underlay} key={index}><Image             source={picture.src}             style={{                 width: width - BORDER_RADIUS,                 height:                 ((width - BORDER_RADIUS) * picture.height) / picture.width,                 }}                 /></Animated.View>                );            })}<Animated.ScrollView                 ref={scroll}                horizontal                 snapToInterval={width}                 decelerationRate="fast"                 showsVerticalScrollIndicator={false}                 bounces={false}                {...scrollHandler}>                    {slides.map(({ title, picture }, index) => (<Slide key={index} right={!!(index % 2)} {...{ title, picture }} /> //Üst renkli slider kısmıüzerindeki yazıların konumlandırılması                    ))}</Animated.ScrollView></Animated.View><View style={styles.footer}><Animated.View                 style ={{ ...StyleSheet.absoluteFillObject }} // backgroundColor: "red" eklenirse Sol alt köşe rengi değişir                 /><View style= {styles.footerContent}><View style={styles.pagination} >                      {slides.map((_, index) => (<Dot                       key={index}                       currentIndex={divide(x, width)}                       { ...{index }}                       />                      ))}</View><Animated.View style={{                          flex: 1,                          flexDirection: "row",                          width: width * slides.length,                          transform: [{ translateX: multiply(x, -1) }],                      }}>{slides.map(({ subtitle, description }, index) => (<Subslide                         key={index}                         onPress={() => {                            if(scroll.current) {                                scroll.current                                .getNode()                                .scrollTo({ x: width * (index + 1), animated: true }); // İleri butonuyla bölümü atlama                            }                        }}                        last={index === slides.length - 1 }                         {...{ subtitle, description }}                         />                    ))}</Animated.View></View></View></View>    )}export default Onboarding;

Jest: test fails with "SyntaxError: Cannot use import statement outside a module" React native

$
0
0

I'm trying to run a test but it failes with this error:enter image description herepackage.json

..."jest": {"preset": "react-native"  },...

tsconfig.json

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"isolatedModules": true,"jsx": "react-native","lib": ["es6"],"moduleResolution": "node","noEmit": true,"strict": true,"target": "esnext",  },"exclude": ["node_modules","babel.config.js","metro.config.js","jest.config.js"  ]}

jest.config.js

module.exports = {  preset: 'react-native',  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],  transformIgnorePatterns: ['@react-native-firebase/admob'], };

bable.config.js

module.exports = {  presets: ['module:metro-react-native-babel-preset'],};

Already tried few things but none of them worked.Let me know if something is missing and I'll edit the post.Thanks!

Formik React-Native - How to Show Yup Validation Errors on Each Field in an Array of Objects

$
0
0

So I'm trying to make a list of contacts, here's the code:

Yup Schema:

export const Schema = Yup.object().shape({/**other fields */contacts: Yup.array().required('Required field').of(    Yup.object().required('Required!').shape({        id: Yup.number(),        name: Yup.string().required('Required field!'),        phone: Yup.string().required('Required field!'),        email: Yup.string().email('Type a valid Email!').required('Required field!')    }))})

Formik Component:

const Form = () => {return (<View>  <Formik     validationSchema={Schema}    initialValues: {        /* other values */        contacts: [            {                id: 0,                name: '',                phone: '',                email: ''            }        ]    }>{({ handleChange, handleBlur, handleSubmit, setFieldValue, errors, touched, values }) => {    function addNewContact() {        setFieldValue('contacts', [            ...values.contacts,            { id: values.contacts[values.contacts.length - 1].id + 1, name: '', phone: '', email: '' }        ])    }    return (        /**A lot of inputs here*/        {values.contacts.map(({ id, email, name, phone }, index) => (<View key={id}><Text>Name *</Text><Input                    value={name}                    onChangeText={handleChange(`contacts[${index}].name`)}                    onBlur={handleBlur(`contacts[${index}].name`)}                />                {(errors.contacts ? errors.contacts[index].name : false)&& (touched.contacts ? touched.contacts[index].name : false)&& <Text>{`${errors.contacts[index].name}`}</Text>}                /**Repeat the above with phone and email */</View>        ))}    )}}</Formik></View>)}export default Form

My problem is when displaying the errors, I can't access them. In the way that is written above, intellisense says that name from errors.contacts[index].name does not exist on type string | FormikErrors<IContactProps>

I've tried to remove the ternary operator condition, but it tells me that contacts is possibly undefined.

When I console.log(errors.contacts), it shows the array I was supose to be able to access with errors.contacts[index].name.

Even with that intellisense error, my code runs and works with 1 contact. When I add 2 or more contacts,the app throws when I text on an Input: undefined is not an object (evaluating errors.contacts[index].name)

How can I properly access these errors on an Array of objects? Thanks for your help!

Invariant Violation: Could not find "client" in the context or passed in as an option

$
0
0

I have a very simple react native setup which I am trying to connect to a Graphql server through Apollo.

This is what the only file I modified (after CRNA), looks like:

App.tsx

import React from 'react';import { StyleSheet, ScrollView, Text, FlatList } from 'react-native';import { ApolloProvider, useQuery } from '@apollo/client';import client from './apollo';import gql from 'graphql-tag';export const FETCH_TODOS = gql`query {  todos (    order_by: {      created_at: desc    },    where: { is_public: { _eq: false} }  ) {    id    title    is_completed    created_at    is_public    user {      name    }  }}`;const App: () => React.ReactNode = () => {  const { data, error, loading } = useQuery(    FETCH_TODOS,  );  return (<ApolloProvider client={client}><ScrollView        style={styles.scrollView}><FlatList          data={data.todos}          renderItem={({ item }: any) => <Text>{item}</Text>}          keyExtractor={(item) => item.id.toString()}        /></ScrollView></ApolloProvider>  );};const styles = StyleSheet.create({  scrollView: {    backgroundColor: "white",  }});export default App;

The makeApolloClient file is this:

apollo.ts

import {    ApolloClient,    InMemoryCache,    NormalizedCacheObject,    createHttpLink} from '@apollo/client'function makeApolloClient({ token }: any): ApolloClient<NormalizedCacheObject> {    // create an apollo link instance, a network interface for apollo client    const link = createHttpLink({        uri: `https://hasura.io/learn/graphql`,        headers: {            Authorization: `Bearer ${token}`        }    });    const cache = new InMemoryCache()    const client = new ApolloClient({        link: link as any,        cache    });    return client;}const client = makeApolloClient({ token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9" });export default client;

On running npx react-native run-android, this is the error I get:

Invariant Violation: Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.

Can't figure out what the issue is, since I've already wrapped the only component I have with ApolloProvider.

How to compose ParamList for nested navigators in v5?

$
0
0

Say I have two navigators like this:

export type RootStackParamList = {  Bootstrap: undefined;  Login: undefined;  MainApp: undefined;};export type MainTabsParamList = {  Explore: undefined;  Profile: undefined;};const MainTabs = createBottomTabNavigator<MainTabsParamList>();const MainApp = () => (<MainTabs.Navigator ><MainTabs.Screen      name="Explore"      component={Explore}    /><MainTabs.Screen      name="Profile"      component={Profile}    /></MainTabs.Navigator>);const RootStack = createStackNavigator<RootStackParamList>();const App = () => {  return (<NavigationContainer><RootStack.Navigator initialRouteName="Bootstrap" headerMode="none"><RootStack.Screen name="Bootstrap" component={Bootstrap} /><RootStack.Screen name="Login" component={Login} /><RootStack.Screen name="MainApp" component={MainApp} /></RootStack.Navigator></NavigationContainer>  );};

Now if I want to navigate to Profile screen from Bootstrap screen. I have to write: (navigation prop properly annotated)

navigation.navigate('MainApp', {screen: 'Profile'})

But typescript gives error here. Saying Type '{ screen: string; }' is not assignable to type 'undefined'. This is because typescript doesn't know MainApp has child screens. So I have to somehow compose the ParamLists so typescript knows about the child screens. How do I do that? Does react-navigation v5 support that?

React Native ScrollView Wrapping for Complex Elements

$
0
0

I've got a ScrollView and I'm listing a few Components in it. So far, I'd been putting just one big Text component in the ScrollView and it was wrapping fine. But now that I've created a new Component (in this case, ComplexText), the wrapping is a little off. (The ComplexText components are listed appropriately, it's just that long messages wrap a little funny and the last few characters of each wrapped line fall off of the screen.

Here's a basic form of my code:

import React, { ReactElement } from "react";import {ScrollView, View, Text} from "react-native";interface TextProps {    person: string,    message: string;}const ComplexText = ({person, message} : TextProps) : ReactElement => {    return (<View style={{flexDirection: "row"}}><Text textBreakStrategy={"simple"} style={{fontSize: 20, fontWeight: "bold"}}>{person +": "}</Text><Text textBreakStrategy={"simple"} style={{fontSize: 20}}>{message}</Text></View>    );};const ScrollingComplexText = () : ReactElement => {    return (<><View style={{flex:0.05}} key={"status-bar-background"}/><ScrollView style={{backgroundColor: "lightblue"}} key={"scrolling-messages"}><ComplexText person={"Samantha"} message={"Hello Anthony."} /><ComplexText person={"Anthony"} message={"Hello Samantha."} /><ComplexText person={"System"} message={"User Jonathan has joined the chat, say something to welcome him."} /><ComplexText person={"Anthony"} message={"Hello Jonathan."} /><ComplexText person={"Samantha"} message={"Hello Jonathan."} /><ComplexText person={"Jonathan"} message={"Hello everybody."} /></ScrollView></>    );};export default ScrollingComplexText;

And here's a screenshot of the issue (as you can tell, most of the word something is being cut off):enter image description here

RealmJS TypeError: Cannot read property 'Realm' of undefined

$
0
0

This is an issue I had with RealmJS while working on my React Native app. I spent over four days trying to debug what was going wrong (I had already built a significant portion of the app, thinking it would be patched out in a newer release). Hopefully this helps someone.


I am trying to debug my React Native application but cannot due to RealmJS. When I run my simulator or device (either iOS or Android), the app works perfectly fine. Turn on Remote Debug, however, and the app just hangs on launch. I get the following error along with a blank white screen:

TypeError: Cannot read property 'Realm' of undefined   reactConsoleErrorHandler  @  ExceptionsManager.js:179   n  @  backend.js:32   reportException  @  ExceptionsManager.js:104   handleException  @  ExceptionsManager.js:171   handleError  @  setUpErrorHandling.js:24   reportFatalError  @  error-guard.js:49   guardedLoadModule  @  require.js:204   metroRequire  @  require.js:128   (anonymous)  @  index.js:118   executeApplicationScript  @  RNDebuggerWorker.js:2   (anonymous)  @  RNDebuggerWorker.js:2

I've tried reseting the cache (watchman, react-native, pods, etc.), cleaning the build folder, and even restarting my machine, but nothing seems to work. Installing Realm in a fresh project shows that it works just fine, but I don't want to have to redo my entire project. What am I doing wrong?

Setup (npx react-native info):

System:    OS: macOS 10.15.5    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz    Memory: 230.89 MB / 16.00 GB    Shell: 5.7.1 - /bin/zsh  Binaries:    Node: 14.12.0 - /usr/local/bin/node    Yarn: 1.22.4 - /usr/local/bin/yarn    npm: 6.14.8 - ~/Projects/MyApp/node_modules/.bin/npm    Watchman: 4.9.0 - /usr/local/bin/watchman  Managers:    CocoaPods: 1.9.3 - /usr/local/bin/pod  SDKs:    iOS SDK:      Platforms: iOS 13.6, DriverKit 19.0, macOS 10.15, tvOS 13.4, watchOS 6.2    Android SDK: Not Found  IDEs:    Android Studio: 4.0 AI-193.6911.18.40.6626763    Xcode: 11.6/11E708 - /usr/bin/xcodebuild  Languages:    Java: 14.0.2 - /usr/bin/javac    Python: 2.7.16 - /usr/bin/python  npmPackages:    @react-native-community/cli: ^4.13.0 => 4.13.0     react: 16.13.1 => 16.13.1     react-native: 0.63.3 => 0.63.3     react-native-macos: Not Found  npmGlobalPackages:    *react-native*: Not Found

Why does this request only work if I have the react-native-debugger running?

$
0
0

I have a very strange problem: I am sending an axios request to my local computer in my React Native app.

This is the code for the request:

const client = axios.create({    baseURL: 'https://192.168.178.20:5000/',    headers: {'Content-Type': 'application/x-www-form-urlencoded'    }});const params = new URLSearchParams();params.append('scope', 'openid profile offline_access email');params.append('username', '<username>');params.append('password', '<password>');const response = await client.post<AuthResponse>('connect/token', params);

But the request only reaches my backend (Which is running on https://192.168.178.20:5000/) if I have activated remote debugging in the expo app and react-native-debugger opened. Otherwise I get this AxiosError:

{"message":"Network Error","name":"Error","stack":"createError@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:142265:26\nhandleError@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:142169:27\ndispatchEvent@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:32672:31\nsetReadyState@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:31756:33\n__didCompleteResponse@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:31572:29\nemit@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:3921:42\n__callFunction@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:3149:36\nhttp://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:2881:31\n__guard@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:3103:15\ncallFunctionReturnFlushedQueue@http://192.168.178.20:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:2880:21\ncallFunctionReturnFlushedQueue@[native code]","config":{"url":"connect/token","method":"post","data":"scope=openid profile offline_access whee_api email&username=bob&password=BobDerBaumeister5%2B&client_id=whee_mobile&grant_type=password","headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/x-www-form-urlencoded"},"baseURL":"https://192.168.178.20:5000/","transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1}}

I really have no idea what the react-native-debugger has to do with this axios request.

I am using this versions:

  • React Native: 0.63.23
  • Expo: 39.0.3
  • Axios: 0.20.0
  • React Native Debugger: 0.11.5

Any more details needed?

React Native how can I read QR code from gallery

$
0
0

I have the functionality to Scan QR to view the profile of a person. Everything is working fine but I also want a functionality to decode/to read QR from my gallery instead of scanning it.

So it would go like this.

  1. Users can Scan QR to view profiles.
  2. There's an option above that the user can import the QR code image from the gallery and once it's imported it will decode the image if its a correct QR or not.
  3. If the QR is correct and it exists in DB then go to the user profile.
  4. If not return an error saying either an invalid qr or user does not exist.

I think Apps like LINE, WeChat have this functionality instead of scanning the QR they can just save the QR code into their library sent by their friend or another user then import that and decode it or read and then tadah.

What I had in mind is first I need a native library for reading my gallery. Once the user selected I need a library or functionality to read/decode the image if its a QR code or not.

How can I achieve this? I did some googling and research already but I haven't found an existing library for that.

Appreciate it if someone could help.Thanks

type for material UI icons

$
0
0

I have a component that looks like this:

type IconButtonProps = { text: string ; onClick: () => void, icon: any};export const IconButton: FunctionComponent<IconButtonProps> = ({  text,  onClick,  icon,}) => {  const classes = useStyles();  return (<Button className={classes.button}     onClick={onClick}>     {''}    {icon}     {text}</Button>  );};

and is called like this:

import SearchIcon from '@material-ui/icons/Search';<IconButton text={'Search'} icon={<SearchIcon />} onClick={()=>SearchUsers()}></IconButton>

In the props, I am using any as the icon's type. What's the correct type to use? I want to avoid using any type.

Searching in header and updating component

$
0
0

In my React Native app I have an infinite scroll (FlatList) and need to be able to search for specific items. Now the problem I have is that I have an onEndReached event that loads in more data which looks like this:

onEndReached={() => {    props.fetchOrders('', offset, 10);    setOffset(offset + 10);}}

The API call happens and my Redux state gets updated with the orders and the orders then get added to my FlatList with a useEffect hook that depends on the items in the Redux state:

useEffect(() => {  if (props.orders.length > 0) {    setIsLoading(false);    setOrders([...orders, ...props.orders])  } else {    setIsLoading(true);  }}, [props.orders])

Now in the header component of the FlatList there should be a SearchBar where I can search for specific items which triggers an API call which then updates the Redux state which then triggers my useEffect hook and updates the items in the FlatList. The problem is that with my current useEffect hook my items just get appended to my FlatList instead of overwriting it. Is there a clean solution on how to implement this or is my useEffect method just not suited for my needs?

mobx state not updating

$
0
0

When I click on the button titled increment,I want the count to get incremented and reflect the change. The state variable "count" is not getting incremented on click. What am I missing?

The App file looks like this:

App.tsx

import { StatusBar } from 'expo-status-bar';import React, { useContext, useState }from 'react';import { Button, StyleSheet, Text, View } from 'react-native';import { observer } from 'mobx-react-lite';import { CounterStoreContext } from './stores/CounterStore';const App = observer(() => {  const counterStore = useContext(CounterStoreContext);  return (<View style={styles.container}><Text>Heyyy</Text>      {console.log(counterStore.count)}<Text> {counterStore.count}</Text><StatusBar style="auto" /><Button title='increment' onPress={() => counterStore.count++}/></View>  );});const styles = StyleSheet.create({  container: {    flex: 1,    backgroundColor: '#fff',    alignItems: 'center',    justifyContent: 'center',  },});export default App;

Context file looks like this:./stores/CounterStore.tsx

import { observable } from 'mobx';import { createContext } from "react";class CounterStore {    @observable count = 1;}export const CounterStoreContext = createContext(new CounterStore());

getTheme() native base Type

$
0
0

I'm using a custom Native Base style theme as described in this link.

https://docs.nativebase.io/Customize.html#theaming-nb-headrefImports:

import material from './native-base-theme/variables/material';import getTheme from './native-base-theme/components';
return (<Suspense fallback="loading"><Provider store={store}><StyleProvider style={getTheme(material)}>

Inside getTheme(), on material, I get this TypeScript error:

Argument of type '{ platformStyle: string; platform: "ios" | "android"| "windows" | "macos" | "web"; headerStyle: string; iconStyle: string;contentStyle: string; expandedIconStyle: string; accordionBorderColor:string; ... 151 more ...; Inset: { ...; }; }' is not assignable toparameter of type '{ platformStyle: any; platform: "ios" | "android" |"windows" | "macos" | "web"; accordionBorderColor: string;accordionContentPadding: number; accordionIconFontSize: number;contentStyle: string; ... 180 more ...; Inset: { ...; }; }'. Type '{platformStyle: string; platform: "ios" | "android" | "windows" |"macos" | "web"; headerStyle: string; iconStyle: string; contentStyle:string; expandedIconStyle: string; accordionBorderColor: string; ...151 more ...; Inset: { ...; }; }' is missing the following propertiesfrom type '{ platformStyle: any; platform: "ios" | "android"

How do I get rid of this?

inside the native-base-themes folder, there's a material.js file that looks like this:

import color from 'color';import { Platform, Dimensions, PixelRatio } from 'react-native';import { PLATFORM } from './commonColor';const deviceHeight = Dimensions.get('window').height;const deviceWidth = Dimensions.get('window').width;const platform = Platform.OS;const platformStyle = PLATFORM.MATERIAL;const isIphoneX =  platform === PLATFORM.IOS &&  (deviceHeight === 812 ||    deviceWidth === 812 ||    deviceHeight === 896 ||    deviceWidth === 896);export default {  platformStyle,  platform,  // Android  androidRipple: true,  androidRippleColor: 'rgba(256, 256, 256, 0.3)',  androidRippleColorDark: 'rgba(0, 0, 0, 0.15)',  buttonUppercaseAndroidText: true,  // Button  buttonFontFamily: 'Roboto',  get buttonPrimaryBg() {    return this.brandPrimary;  },  get buttonTextSizeLarge() {    return this.fontSizeBase * 1.5;  },  // Header  toolbarBtnColor: '#fff',  toolbarDefaultBg: '#3F51B5',  toolbarHeight: 56,  toolbarSearchIconSize: 23,  toolbarInputColor: '#fff',  searchBarHeight: platform === PLATFORM.IOS ? 30 : 40,  searchBarInputHeight: platform === PLATFORM.IOS ? 40 : 50,  toolbarBtnTextColor: '#fff',  toolbarDefaultBorder: '#3F51B5',  iosStatusbar: 'light-content',  get statusBarColor() {    return color(this.toolbarDefaultBg)      .darken(0.2)      .hex();  },  get darkenHeader() {    return color(this.tabBgColor)      .darken(0.03)      .hex();  },  // Text  textColor: '#000',  inverseTextColor: '#fff',  noteFontSize: 14,  get defaultTextColor() {    return this.textColor;  },  // iPhoneX SafeArea  Inset: {    portrait: {      topInset: 24,      leftInset: 0,      rightInset: 0,      bottomInset: 34,    },    landscape: {      topInset: 0,      leftInset: 44,      rightInset: 44,      bottomInset: 21,    },  },};

react native metro server is exiting after installing application on linux [closed]

$
0
0

I have a react native project and Iam trying to run on a android real device , but after installing application (loads old codes of application new changes not showing) metro server is exiting .I'am using linux 20(Focal Fossa) .can any one help me with this issue.


How to override typescript definition correctly

$
0
0

I created a definition file to override the one from the library but the one from the library seems to have a higher priority

.├── android├── app.json├── babel.config.js├── index.ts├── ios├── metro.config.js├── node_modules├── package.json├── src│  ├── customTypes│  │  └── react-native-track-player│  │   |    └── index.d.ts├── __tests__├── tsconfig.json├── tsc.txt├── yarn-error.log└── yarn.lock

The tsconfig :

{"compilerOptions": {"allowJs": false,"allowSyntheticDefaultImports": true,"experimentalDecorators": true,"jsx": "react-native","module": "es2015","moduleResolution": "node","noImplicitAny": false,"noImplicitReturns": true,"noImplicitThis": true,"noUnusedLocals": true,"sourceMap": true,"target": "esnext","lib": ["esnext"],"skipLibCheck": true,"strict": true,"typeRoots": ["src/customTypings","node_modules/@types"    ]  },"exclude": ["node_modules"],"include": ["index.ts"  ]}

When using the traceResolution the compiler resolves the module from cache which does not help to debug :

======== Resolving module 'react-native-track-player' from '/projects/TwoUApp/src/player/ProgressBarMusic.tsx'. ========Resolution for module 'react-native-track-player' was found in cache from location '/projects/TwoUApp/src/player'.======== Module name 'react-native-track-player' was successfully resolved to '/projects/TwoUApp/node_modules/react-native-track-player/index.d.ts' with Package ID 'react-native-track-player/index.d.ts@1.2.3'. ========

How can I override the type definition file or at least invalidate the cache to debug ?

Thanks for your help.

Styles not injected via props in material-ui typescript component in react native

$
0
0
import {createStyles, WithStyles} from "@material-ui/core";const styles = (theme: Theme) => createStyles({    root: {}});interface MyProps extends WithStyles<typeof styles> {}export class MyComponent extends Component<MyProps> {    constructor(props: MyProps) {         super(props);        console.log(props.classes); // why this is undefined?     }}

Why props.classes is undefined?

React Native | How access to endCoordinates of Keyboard using Typescript and recompose

$
0
0

So I use recompoose and typescript in my react native app, and I trying to access to endCoordinates for Keyboard the get the Keyboard height. I followed this article and this post but I am not able to access to endCoordinates, it's always undefined.

This is what I tried :

const withLifeCycle = lifecycle<Handlers, {}> ({     componentDidMount() {        // @ts-ignore        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.props._keyboardDidShow)}, componentWillUnmount() {   // @ts-ignore   this.keyboardDidShowListener.remove(); }})    interface Handlers {  _keyboardDidShow: (e:any) => void;}// WrappedProps have some other props for some other part of codesexport const enhance = compose<WrappedProps, Props>(withHandlers<Props,{}>({  _keyboardDidShow: (e) => () =>{     console.log(e.endCoordinates) // This is Undefined   } }), withLifeCycle);

I think the problem is the way I need to pass the keyboardDidShow event type to the method, because e object does not have any endCoordinates.

React-native version mismatch after upgrading my react-native app from 0.55.3 to 0.59.2

$
0
0

I have a react-native app which was working perfectly in verson 0.55.3.Now I have upgraded it to 0.59.2. it builds fine and gets installed on android device. but when if opened it gives the error log in the picture.I have tried reseting the following solutions:

  1. reseting cashe
  2. removing node_modules folder and yarn.lock file and then installing again
  3. running the upgrade command to 0.59.2
  4. uninstalling the app from my android and then reinstalling it
  5. restarting my pc
  6. closing all other terminals

I have made all the recommended modifications for the upgrade(using the react-native upgrade helper) in files like build.gradle(app), build.gradle(android), setting.gradle, Mainapplication.java, androidmenifest.xml.

enter image description here

below is my packege.json file:

"dependencies": {"@react-native-community/cli-platform-android": "2.0.2","@react-native-firebase/analytics": "6","@react-native-firebase/app": "8.3.0","@react-native-firebase/auth": "8.3.1","@react-native-firebase/crashlytics": "8.3.0","@react-native-firebase/iid": "6","@react-native-firebase/messaging": "6","@types/base-64": "^0.1.2","@types/intl": "^1.2.0","@types/isomorphic-fetch": "^0.0.34","@types/node": "^9.6.4","@types/react": "16.3.16","@types/react-intl": "^2.3.5","@types/react-native-fetch-blob": "^0.10.4","@types/react-native-loading-spinner-overlay": "^0.5.1","@types/react-navigation": "1.5.5","@types/react-redux": "5.0.20","base-64": "^0.1.0","cross-fetch": "^2.1.0","fbjs": "^0.8.16","fuzzyset.js": "^0.0.5","intl": "^1.2.5","is-container": "^2.0.0","promise.allsettled": "^1.0.2","react": "16.8.3","react-intl": "^2.4.0","react-loading-overlay": "^1.0.1","react-native": "0.59.2","react-native-fetch-blob": "^0.10.8""react-native-image-picker": "^2.3.4","react-native-loading-spinner-overlay": "^1.0.1","react-native-material-ui": "^1.20.0","react-native-openalpr": "^2.1.1","react-native-signature-canvas": "1.4.2","react-native-snackbar": "^2.0.0","react-native-step-indicator": "^0.0.11","react-native-typescript-transformer": "^1.2.13","react-native-vector-icons": "4.5.0","react-navigation": "^1.5.12","react-redux": "^5.0.7","react-spinners": "^0.6.1","redux": "^3.7.2","redux-persist": "^5.10.0","redux-saga": "^0.16.0","redux-thunk": "2.3.0","ts-jest": "25","tslint": "^5.9.1","tslint-react": "^3.5.1","typesafe-actions": "^1.1.2","typescript": "3.8.3","utility-types": "^1.1.0"  }

any help is much appreciated. thank you!

React Navigation Error - TypeScript - This Expression Is Not Callable

$
0
0

I'm trying to find the best practice for this typescript issue I'm experiencing when I upgraded to React Navigation 5. The error I'm getting is

This expression is not callable.  Each member of the union type '{ <RouteName extends "Stack1Screen1" | "Home">(...args: undefined extends SampleParamList1[RouteName] ? [RouteName] | [RouteName, SampleParamList1[RouteName]] : [...]): void; <RouteName extends "Stack1Screen1" | "Home">(route: { ...; } | { ...; }): void; } | { ...; }' has signatures, but none of those signatures are compatible with each other.ts(2349)

Here is the code I'm essentially using:

import { StackScreenProps } from '@react-navigation/stack';export type SampleParamList1 = {  Stack1Screen1: undefined;  Home: undefined;};export type SampleParamList2 = {  Stack2Screen2: undefined;  Home: undefined;};type Props =  | StackScreenProps<SampleParamList1, 'Stack1Screen1'>  | StackScreenProps<SampleParamList2, 'Stack2Screen2'>;const ThisScreen: React.FC<Props> = ({ navigation, route }) => {  const navToHome = () => navigation.navigate('Home');};

Hovering over the navigation.navigate('Home') function displays the error message.Any ideas on how to solve this? Thanks! :)

Viewing all 6213 articles
Browse latest View live


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