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

how to use navigation.replace in TypeScript?

$
0
0

I am trying to use this in my code:

const navigation = useNavigation();navigation.replace('AllFriends')

But I keep getting an error that:

Property 'replace' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.

I also tried using this

const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()navigation.replace('route');

as suggested here: https://github.com/react-navigation/react-navigation/issues/8256

but this gives me an error on replace that expected 2 arguments but got only 1...

I am using "@react-navigation/native": "^5.5.1",


Property 'pop' does not exist on type 'NavigationProp'

$
0
0

How can we use the pop() function in React Native Navigation?

onPress={() => navigation.pop('Home')}>

gives me a TypeScript error that

Property 'pop' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.ts(2339

Fix Position of a FlatList

$
0
0

I am using a FlatList in my code like this:

<View style={styles.listHolder}>          {data && (<FlatList              data={data.me.friends.nodes}              horizontal={false}              scrollEnabled              renderItem={({ item }) => (<FriendItem friend={item} originatorId={data.me.id}/>              )}              keyExtractor={(item) => item.id.toString()}              ListEmptyComponent={NoFriendsContainer}            />          )}          {error && <ErrorContainer />}</View>  listHolder: {    width: '100%',    alignItems: 'center',  },

Each of the FriendItem looks somewhat like this:

 return (<View style={styles.item}><TouchableOpacity        onPress={() =>          navigation.navigate('FriendDetails', {            firstName: friend.firstName,            rating: friend.rating,            numberOfFriends: friend.friendsOfFriends?.totalCount,            //onDeleteFriend: onDeleteFriend,            vehicles: friend.vehicles,          })        }><Thumbnail          style={styles.thumbnail}          source={{            uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',          }} /></TouchableOpacity><View style={styles.nameContainer}><Text style={styles.userName}>{userName}</Text></View><View style={styles.deleteButtonContainer}><Button          rounded          style={styles.deleteButton}          onPress={() => onDeleteFriend(originatorId, friend.id)}><Icon name="trash-o" size={moderateScale(20)} color="black" /></Button></View></View>  );};export const styles = StyleSheet.create({  item: {    backgroundColor: 'white',    borderRadius: moderateScale(20),    padding: moderateScale(20),    marginVertical: moderateScale(8),    marginHorizontal: 16,    height: moderateScale(110),    width: moderateScale(360),    justifyContent: 'space-between',    flexDirection: 'row',  },  userName: {    paddingRight: 55,    paddingLeft: 10,    paddingTop: 20,  },  deleteButton: {    backgroundColor: '#31C283',    width: moderateScale(45),    justifyContent: 'center',  },  deleteButtonContainer: {    paddingTop: 12,    marginRight: 2,  },  thumbnail: {    height: 85,    width: 85,    marginLeft: 2,    paddingRight: 0,    position: 'relative',  },  nameContainer: {    flexDirection: 'row',  },});

Now the problem is that the FlatList is rendered vertically but its scroll bar is shown horizontally (which shouldn't happen). Additionally, I can move it in any direction right now. This should also not happen. I must fix it as it is. How can I do so? I am not sure if this is a styling issue or something in the FlatList component.

enter image description here

FlatList hides on scrolling

$
0
0

I am using a FlatList which may have only one item or many items. However, when I only have one item, I would prefer it to be fixed somehow. Currently, if I hold it and scroll it down, it starts to hide. How can I fix this?

If I use scrollEnabled={false} then it becomes inconvenient in cases where I have multiple Items from the FlatList because then I cannot scroll the screen and see the remaining items.

<View style={styles.listHolder}>          {data && <FlatList            data={data.me.pendingUserRelationsRequestsSent.nodes}            horizontal={false}            renderItem={({ item }) => (<UserItem                user={item}                originatorId={data.me.id}              />            )}            keyExtractor={(item) => item.id.toString()}            ListEmptyComponent={NoRequestsContainer}          />            }          {error && <ErrorContainer />}</View>  listHolder: {    width: '100%',  },

UserItem.tsx

 return (<View style={styles.item}><Thumbnail          style={styles.thumbnail}          source={{            uri:'https://cdn4.iconfinder.com/afro_woman_female_person-512.png',          }}></Thumbnail><View style={styles.nameContainer}><Text style={styles.userName}>{userName}</Text></View><View style={styles.buttonContainer}><Button          rounded          style={styles.cancelButton}          onPress={() => onCancelRequest(originatorId, user.id)}><Icon name="close" size={moderateScale(20)} color="black" /></Button></View></View>  );};export const styles = StyleSheet.create({  item: {    backgroundColor: 'white',    borderRadius: moderateScale(20),    padding: moderateScale(20),    marginVertical: moderateScale(8),    marginHorizontal: 16,    height: moderateScale(110),    //width: moderateScale(360),    justifyContent: 'space-between',    flexDirection: 'row',  },  userName: {    paddingTop: 20,  },  buttonContainer: {    paddingTop: 12,    marginRight: 2,    flexDirection: 'row',    justifyContent: 'space-between',  },  cancelButton: {    backgroundColor: '#e8403a',    width: moderateScale(45),    justifyContent: 'center',  },  thumbnail: {    height: 85,    width: 85,    marginLeft: 2,    paddingRight: 0,    position: 'relative',  },  nameContainer: {    flexDirection: 'row',    paddingRight: 30,  },});

enter image description here

Since I drag it down, a lot of space comes on its top too. That shouldn't happen either.

Why is the navigation in react native not working?

$
0
0

I'm working with my Expo-React-Native project and I created my navigation with React Navigation. I have a list of Stores and a detail page for each one of them. This is how I'm doing it:

Stores.tsx

export default function Stores({ navigation }: any) {   //...   return (<FlatList        data={data.allStores}        renderItem={(store) => (<Store            title={store.item.name}            onPress={() =>              navigation.navigate("StoreDetail", {                title: store.item.title,              })            }          />        )}        keyExtractor={(store, index) => String(index)}></FlatList>    );}

StoreDetail.tsx

export default function StoreDetail({ route, navigation }: any) {  return (<View style={styles.container}><ImageBackground        style={styles.image}        source={require("../assets/SampleStore.jpg")}><TouchableOpacity onPress={navigation.goBack()}><Ionicons            style={styles.backIcon}            name="md-arrow-round-back"            size={30}            color={colors.iceWhite}          /></TouchableOpacity></ImageBackground><View style={styles.content}><PrimaryText textAlign={"center"} fontSize={30} margin={7}>          {route.params?.title}</PrimaryText><TouchableOpacity style={styles.button}><PrimaryText color={colors.iceWhite} fontSize={16}>            SACAR TURNO</PrimaryText></TouchableOpacity></View></View>  );} // then the syles...

And for the "wrapper" in which I manage my navigations I have this:

import React from "react";import { Ionicons } from "@expo/vector-icons";import colors from "../../assets/constants/style-variables";import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";import { createStackNavigator } from "@react-navigation/stack";import { NavigationContainer } from "@react-navigation/native";import Turnos from "../MisTurnos";import Stores from "../Stores";import User from "../User";import StoreDetail from "../StoreDetail";const Tab = createBottomTabNavigator();const StoreNav = createStackNavigator();function StoreStack() {  return (<StoreNav.Navigator initialRouteName="Stores"><StoreNav.Screen name="StoreDetail" component={StoreDetail} /><StoreNav.Screen name="Stores" component={Stores} /></StoreNav.Navigator>  );}export default function HomeNavigation() {  return (<Tab.Navigator      tabBarOptions={{        showLabel: false,        style: { backgroundColor: colors.iceWhite },      }}><Tab.Screen        name="Turnos"        component={Turnos}        options={{          tabBarIcon: ({ focused }) => (<Ionicons              name="md-checkbox"              size={20}              color={focused ? colors.primary : colors.iconColor}            />          ),        }}      /><Tab.Screen        name="Stores"        component={StoreStack}        options={{          tabBarIcon: ({ focused }) => (<Ionicons              name="md-basket"              size={20}              color={focused ? colors.primary : colors.iconColor}            />          ),        }}      /><Tab.Screen        name="User"        component={User}        options={{          tabBarIcon: ({ focused }) => (<Ionicons              name="md-person"              size={20}              color={focused ? colors.primary : colors.iconColor}            />          ),        }}      /></Tab.Navigator>  );}

The problem is that whenever I tap on a store, It'll simply do nothing, I checked if there was a problem with items overlapping, but I didn't find any. What am I missing here?

Fix the search results on top of a container

$
0
0

I have a screen that looks like this:

return (<SafeAreaView><View style={styles.container}><View style={styles.topContainer}><View style={styles.searchFieldContainer}><FavoritePointInput              textChangeHandler={textChangeHandler}            /></View><LocationsFound            addressesFound={locations.favAddressesFoundList}          />          {/* <View style={styles.fixed}> */}<View style={styles.fieldDescription}><Text>Set Location's Name:</Text></View><View style={styles.searchFieldContainer}><Item style={styles.searchField}><Input                placeholder="Library"                onChangeText={(text) => setLocationName(text)}                style={styles.searchText}              /></Item></View><View style={styles.buttonContainer}><Button style={styles.button}><Text>Save Location</Text></Button></View></View></View>      {/* </View> */}</SafeAreaView>  );

Its Stlyes are as like this:

export const styles = StyleSheet.create({  container: {    height: '100%',    width: '100%',  },  topContainer: {    height: moderateScale(750),  },  topTextContainer: {    flexDirection: 'row',    justifyContent: 'space-between',    marginVertical: moderateScale(15),    height: moderateScale(30),    paddingLeft: moderateScale(30),    paddingRight: moderateScale(30),  },  topMiddleContainer: {    alignItems: 'center',  },  topMiddleText: {    justifyContent: 'center',    paddingBottom: 40,  },  searchFieldContainer: {    alignItems: 'center',    height: moderateScale(120),  },  button: {    width: moderateScale(120),    borderRadius: moderateScale(20),    alignItems: 'center',    alignContent: 'center',  },  buttonContainer: {    flexDirection: 'row',    justifyContent: 'center',  },  searchField: {    width: moderateScale(300, 0.3),    height: verticalScale(40),    marginVertical: moderateScale(3),    borderRadius: verticalScale(10),  },  fieldDescription: {    alignItems: 'center',  },  fixed: {    position: 'absolute',  }});

When I write something in the first input field, I get search results through the LocationsFound component. That disturbs the whole style and pushes the second input field downwards. I want it to simply overlap and come on top of the second field until one of them is selected. Is that possible?

enter image description here

enter image description here

Configuring Jest in react-native

$
0
0

I'm trying to setup a react-native project with expo (v38) and typescript (v3.9.4).Running into issues with setting up testing, specifically jest.

So I've been following the testingjavascript course and setting up similar to that (if that helps with context at all), so I'm trying to setup linting to run via the projects in the jest config via jest-runner-eslint, here is the full config as it stands:

module.exports = {  preset: '@testing-library/react-native',  transform: {'^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js','\\.(ts|tsx)$': 'babel-jest','^.+\\.(ts|tsx)?$': '<rootDir>/jest-preprocess.js',  },  transformIgnorePatterns: ['node_modules/(?!(react-native|@sentry/react-native||@react-native-community/async-storage|react-native-iphone-x-helper)|react-native-gesture-handler|@react-native-community/masked-view|@react-navigation/stack|tipsi-stripe/)',  ],  moduleFileExtensions: ['ts', 'tsx', 'js'],  moduleNameMapper: {'^src/(.*)$': '<rootDir>/src/$1',  },  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',  timers: 'fake',  testEnvironment: 'jsdom',  projects: [    {      displayName: 'clientTest',      testMatch: ['<rootDir>/src/__tests__/**/*.tsx'],      testEnvironment: 'jest-environment-jsdom',      setupFilesAfterEnv: ['<rootDir>/jest-setup.js'],    },    {      runner: 'jest-runner-eslint',      displayName: 'lint',      testMatch: ['<rootDir>/src/**/*.tsx'],    },  ],};

So if I comment out the projects setting my test runs just fine.When I re-enable only the linting project, it runs those without error but without the tests of course.I can't enable the clientTest project without this error:

    /Users/ko/git/punchline/node_modules/react-native/Libraries/ReactNative/AppContainer.js:22    type Context = {rootTag: number, ...};         ^^^^^^^    SyntaxError: Unexpected identifier      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1258:14)      at Object.<anonymous> (node_modules/@testing-library/react-native/dist/index.js:37:44)

I've tried a multitude of configuration options (too many to list concisely), I've tried adjusting the transformIgnorePatterns, setting different presets, and using different babel presets of which my current babel.config.js is:

module.exports = function (api) {  api.cache(true);  return {    presets: [      ['@babel/preset-env', { targets: { node: 'current' } }],'@babel/preset-react','babel-preset-expo','@babel/preset-typescript','module:metro-react-native-babel-preset',    ],  };};

Any pointers of where I need to go to get things transpiling properly? I just find it weird that the tests work if the jest.config.js doesn't have the project defined.

How to show App intro slider once built on expo using typescript using asyncStorage

$
0
0

I'm using react-native-app-intro-slider to show an onboarding for my app built on expo using typescript. I want the slider to only show for the first time during launch but seem to be having trouble with it.

I'm quite new to typescript but I've looked around and all of the solutions seem to be for react native using asyncStorage.

Not sure if I'm doing it right here.

import AsyncStorage from '@react-native-community/async-storage'const data = [{...}, {...}, {...}]AsyncStorage.setItem('showIntro', 'true')function App() {  { (AsyncStorage.getItem('showIntro') === 'true') ? (<AppIntroSlider        renderItem={renderItem}        data={data}        onDone={onDone}/>      ) : (<ShowApp />      )    } }

How to convert timestamp value to specific time format using react native?

$
0
0

In my scenario, I need to convert timestamp value to specific time format in react native. I tired below code but can't able to achieve exact formate output. How to achieve it?

 var dateTime = new Date(23456789 * 1000);    this.setState({DateTime:('0'+ dateTime.getUTCDate()).slice(-2) +'/'+ ('0'+ dateTime.getUTCMonth()).slice(-2) +'/'+ dateTime.getUTCFullYear() +''+ ('0'+ dateTime.getUTCHours()).slice(-2)        });

Exact output expecting : Wed, 2/01/2000 - 1.10 AM

[React-Native]: No matching version found for @types/react-test-renderer@16.13.1

$
0
0

I'm having issues trying to initialize a react-native project using the typescript template

I've followed the instructions for windows targeting android. As it installs the dependencies, this pops up

npm ERR! code ETARGETnpm ERR! notarget No matching version found for @types/react-test-renderer@16.13.1.npm ERR! notarget In most cases you or one of your dependencies are requestingnpm ERR! notarget a package version that doesn't exist.npm ERR! notargetnpm ERR! notarget It was specified as a dependency of 'awesomeproject'npm ERR! notargetnpm ERR! A complete log of this run can be found in:npm ERR!     C:\Users\olive\AppData\Roaming\npm-cache\_logs\2020-07-10T10_39_02_715Z-debug.log

This is after running npx react-native init AwesomeProject --template react-native-template-typescript

checking out the log file, I get this:

3333 error notarget No matching version found for @types/react-test-renderer@16.13.1.3334 error notarget In most cases you or one of your dependencies are requesting3334 error notarget a package version that doesn't exist.3334 error notarget3334 error notarget It was specified as a dependency of 'awesomeproject'

I've tried initializing it using the default javascript template npx react-native init AwesomeProjectjs and it works with no issue.

I would like to use typescript. What could be the issue and how can it be solved?

Is there an interface type I can use in an interface?

$
0
0

I want to pass an object to a react component as well as the object's interface. Here's an example of an interface I want to use:

interface TableProps {  ObjectProps: Interface (doesn't work);  objects: Array<ObjectProps>;}

Is this at all possible?

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

Pass function with parameters in context provider

$
0
0

I am starting on React and I am finding it difficult to implement the email and password in the context.

The example I'm following only shows no parameters.

Ty for any help

async function signIn(email: string, password: string) {        const response = await auth.signIn(email, password);    }     return (<AuthContext.Provider          value={{signed: !!user,             user: user, loading,             signIn: signIn(),             logout}}>          {children}</AuthContext.Provider>      );

Too many re-renders. When setting state

$
0
0

I'm trying to make an e-commerce app using expo with typescript and I'm having issues with loading my categories page.There's two ways which one can access the category page

  1. Through bottom nav - this one works fine
  2. Through buttons on the home page

Trying to setState based off the params that's coming in through the homepage but it's giving me the Too many re-renders error.Below is the code that I currently have for it.

The default needs to be there because of the first method of entering the category page, I've tried putting a conditional as the default category, but category wont change the second time if being accessed through the home page again.

export default function CategoryList(props: Props) {  let { params } = useRoute<StackRouteProp<'Home'>>()  const [currentCategory, setCategory] = useState({categories: Categories[0]});  if (params) {    setCategory({categories: params.categories})  }}

unable to reset Input field

$
0
0

On my screen, I have an input field that looks like this:

export const FavouritePointInput: React.FunctionComponent<FavouritePointInputProps> = ({  getMyLocationCoordinates,  textChangeHandler,  handleFocus,  favouritePoint,}) => {  return (<Item style={styles.searchField}><TouchableOpacity onPress={getMyLocationCoordinates}><Icon name="search" style={styles.searchIconStyles} /></TouchableOpacity><Input        onFocus={() => {          handleFocus('favouritePoint');        }}        onChangeText={(text) => textChangeHandler('favouritePoint', text)}        style={styles.searchText}        value={favouritePoint}      /></Item>  );};

When I click on the back button on my screen, I use these custom hooks:

const resetLocation = useResetLocation();onPress={() => {                navigation.goBack();                resetLocation('favouriteLocation');              }}>

to resetLocation

This is how the hook looks like:

export const useResetLocation = () => {  const setLocationForPoint = useSetLocationForPoint();  const resetLocation = (fieldName: string) => {    let setAddressAction;    if (fieldName === 'startingPoint') {      setAddressAction = getSetStartPointAction({        coordinates: [],        street: '',      });    }    else {      console.log('fieldname', fieldName);      setAddressAction = getSetFavouritePointAction({        coordinates: [],        street: '',      });    }    setLocationForPoint(setAddressAction);  };
export const getSetFavouritePointAction = (favouritePoint: {  coordinates: number[];  street: string;}) => {  console.log('getSetFavouritePointAction FAV POINT', favouritePoint)  return {    type: LOCATIONS.SET_FAVOURITE_POINT,    payload: favouritePoint,  };};

Whenever I go back, I see the console logs and this console.log('getSetFavouritePointAction FAV POINT', favouritePoint)returns an empty object. However, when I go back to the screen, the word is still written in the input field. The same method is working somewhere else but not here so might be a minor mistake.

Upon going back, I also see logs from here. The state becomes empty when I go back. However, the input field still doesn't become empty.

export default (state = INITIAL_STATE, action) => {  switch (action.type) {    case LOCATIONS.SET_END_POINT:      return { ...state, endPoint: action.payload };    case LOCATIONS.SET_STARTING_POINT:      return { ...state, startingPoint: action.payload };    case LOCATIONS.SET_FAVOURITE_POINT:      console.log('FAVOURITE_POINT');      console.log('state', action.payload )      return { ...state, favouritePoint: action.payload };    default:      return state;  }};

drop down menu hiding behind content

$
0
0

I have a screen that looks like this:

return (<SafeAreaView><View style={styles.container}><View style={styles.topContainer}><View style={styles.searchFieldContainer}><FavoritePointInput              textChangeHandler={textChangeHandler}            /></View><View style={styles.dropdown}><LocationsFound            addressesFound={locations.favAddressesFoundList}          /></View><View style={styles.fieldDescription}><Text>Set Location's Name:</Text></View><View style={styles.searchFieldContainer}><Item style={styles.searchField}><Input                placeholder="Library"                onChangeText={(text) => setLocationName(text)}                style={styles.searchText}              /></Item></View> <View style={styles.buttonContainer}><Button style={styles.button}><Text>Save Location</Text></Button></View></View></View></SafeAreaView>  );

Its Stlyes are as like this:

export const styles = StyleSheet.create({  container: {    height: '100%',    width: '100%',  },  topContainer: {    height: moderateScale(750),  },  topTextContainer: {    flexDirection: 'row',    justifyContent: 'space-between',    marginVertical: moderateScale(15),    height: moderateScale(30),    paddingLeft: moderateScale(30),    paddingRight: moderateScale(30),  },  topMiddleContainer: {    alignItems: 'center',  },  topMiddleText: {    justifyContent: 'center',    paddingBottom: 40,  },  searchFieldContainer: {    alignItems: 'center',    height: moderateScale(120),  },  button: {    width: moderateScale(120),    borderRadius: moderateScale(20),    alignItems: 'center',    alignContent: 'center',  },  buttonContainer: {    flexDirection: 'row',    justifyContent: 'center',  },  searchField: {    width: moderateScale(300, 0.3),    height: verticalScale(40),    marginVertical: moderateScale(3),    borderRadius: verticalScale(10),  },  fieldDescription: {    alignItems: 'center',  },    dropdown:{    position: 'absolute',    top: 200,  }});

When I write something in the first input field, I get search results through the LocationsFound component. However, the search results start to hide behind the second input field. I want it to simply overlap and come on top of the second field until one of them is selected. Is that possible?

enter image description here

React-native: multiple style props in styled-component and typescript

$
0
0

I am using React-native typescript for my app. I am really new in React-native. lots of syntax are new to me. For styling I am using styled-components. I have created global button components. So, I can use it in different components. I want to create conditional size and color of buttons. So, I can manipulate the size and color from parent components. I can do two conditional style props. But i don't know how to do multiple conditions in React-native.

This is my Button component

import React from 'react';import { Text, TouchableHighlight } from 'react-native';import styled, { css } from 'styled-components/native';export interface IButton {  appearance?: "primary" | "secondary" | "dark" | "light";  children?: string | JSX.Element;  size?: "small" | "medium" | "big";  className?: string;  disabled?: boolean;  loading?: boolean;  style?: React.CSSProperties;  onPress?: () => void;}const Button = ({ appearance, children, size, disabled, loading, style, onPress, className }: IButton) => {  return (<ButtonContainer      className={className}      onPress={onPress}      disabled={disabled}      style={        disabled ?          { ...style, "opacity": 0.5, "pointerEvents": `none` } :          loading ?            { ...style, "pointerEvents": `none` } :            style      }>      {loading ? <Label>loading...</Label> : <Label>{children} </Label>}</ButtonContainer>  );};const Label = styled.Text`  color: white;  font-weight: 700;  align-self: center;  padding: 10px;`const ButtonContainer = styled.TouchableHighlight<  {    appearance: IButton["appearance"]; // this is my typescript props I don't know how to connect them with my Button styling.  }>`  width: 50%;  margin-top: 5px;  border-color: grey;  border-width: 2px;  border-radius: 5px;  border-radius: 4px; background-color:${props => props.primary ? "gray" : "blue"} //`export default Button;

This is my the parent component where I am using my button component.

<Button    size="medium" //this is does not work because I did not style yet    onPress={() => console.log('hello')}>    click me </Button>

How can I do React navigation user actions?

$
0
0

My English is not good, I apologize in advance. I am using React native tab menu. But user login and profile sections appear at the same time. For this, I hide it if there is a token. But when I steer, my profile does not appear. It only appears when I click on another tab. I guess it doesn't appear instantly because it waits with await.

let token = null;export default function BottomTabNavigator({ navigation, route }) {  navigation.setOptions({ headerTitle: getHeaderTitle(route) });    _getToken();  return (<BottomTab.Navigator initialRouteName={INITIAL_ROUTE_NAME}>      {token ?<BottomTab.Screen          name="Profile"          component={ProfileScreen}                  options={{            title: 'Profilim',            tabBarIcon: ({ focused }) => <TabBarIcon focused={focused} name="md-person" />,          }}        />       : <BottomTab.Screen          name="Login"          component={LoginScreen}                  options={{            title: 'Giriş Yap',            tabBarIcon: ({ focused }) => <TabBarIcon focused={focused} name="md-person" />,          }}        />}     </BottomTab.Navigator>  );}async function _getToken() {    try {    token = await AsyncStorage.getItem('token');  } catch (error) {    console.log(error);  }};

Using Async Storage for Localization

$
0
0

I have 2 different APIs that I use for localization. These return json.

getEnLoc() //400kbgetEsLoc() //400kb

I want to call them on App.ts while the app is being ready for running and write the returned answer(json object) to async storage. Afterwards, while the any page is being translated, the key-values ​​in the local storage will be checked.

// In App.tsAsyncStorage.setItem('@storage_Key', getEnLoc())// In Home.tsxconst jsonValue = await AsyncStorage.getItem('@storage_Key')

What do you think about this logic? Do you think it causes loss of performance?

Why, even after specifying a type parameter for a React component, the linter still complains about '' missing in props validation?

$
0
0

Please consider the following TypeScript (.tsx) code:

import React from 'react';import { TextInputProps } from 'react-native';import { Container, TextInput, Icon } from './styles';interface InputProps extends TextInputProps {  name: string;  icon: string;}const Input: React.FC<InputProps> = ({ name, icon, ...props }) => (<Container><Icon name={icon} size={20} color="#666360" /><TextInput      keyboardAppearance="dark"      placeholderTextColor="#666360"      {...props}    /></Container>);export default Input;

By passing TextInputProps as a type parameter to React.FC I have access to the TextInput properties, which I'm destructuring in ...props. But I also need name and icon for other purposes, so I created an interface extending TextInputProps, specified these properties there, and passed InputProps to React.FC instead.

Now I get 'name' is missing in props validation - eslintreact/prop-types (same for 'icon'), but this didn't happen when I tried to get any of the properties specified inside TextInputProps.

Writing const Input: React.FC<InputProps> = ({ name, icon, ...props }: InputProps) => (/*...*/); makes the linter stop complaining, but I still don't get why using the type parameter doesn't. Can someone clarify this to me? Am I getting some concept wrong, or is it just a problem with the linter?

PS: I'm writing this on VS Code with ESLint extension.

PS2: This is the code inside styles.ts, if it may help:

import styled from 'styled-components/native';import FeatherIcon from 'react-native-vector-icons/Feather';export const Container = styled.View`  /* Some CSS */`;export const TextInput = styled.TextInput`  /* More CSS */`;export const Icon = styled(FeatherIcon)`  /* ... and CSS */`;
Viewing all 6218 articles
Browse latest View live


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