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

Couldn't find preset "module:metro-react-native-babel-preset" relative to directory

$
0
0

I'm trying to run my test suite but I am getting the following error:

Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "/Users/dan/Sites/X"      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19          at Array.map (<anonymous>)      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)      at File.initOptions (node_modules/ts-jest/dist/util/hacks.js:23:43)      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

Here's my jest config in package.json:

"jest": {"preset": "react-native","moduleFileExtensions": ["ts","tsx","js","jsx","json"    ],"transform": {"^.+\\.(js)$": "<rootDir>/node_modules/react-native/jest/preprocessor.js","\\.(ts|ts)x?$": "ts-jest"    },"testRegex": "/src/.*.spec.(js|ts|tsx)?$","globals": {"ts-jest": {"useBabelrc": true      }    }  }

If needed, here's the contents of babelrc

{"presets": ["module:metro-react-native-babel-preset"],"plugins": [    ["module-resolver",      {"alias": {"~": "./src"        }      }    ]  ]}

combine states for a rating component

$
0
0

I am trying to make a star rating component. I am using ternary operators to check if a state is true or not. If yes, I use a yellow star or else a white one. However, this looks like bad code practice. Instead of repeating all these ternary operators, is it possible to somehow combine the conditions and render only those yellow stars whose state is true?

const [oneStar, setOneStar] = useState(false);const [twoStar, setTwoStar] = useState(false);const [threeStar, setThreeStar] = useState(false);const [fourStar, setFourStar] = useState(false);const [fiveStar, setFiveStar] = useState(false);const ratings = [    1,2,3,4,5]const setRating = (rating: number) => {  console.log('rating', rating);  if(rating == 1){      setOneStar(true);      setTwoStar(false);      setThreeStar(false);      setFourStar(false);      setFiveStar(false);  }  if(rating == 2){    setOneStar(true);    setTwoStar(true);    setThreeStar(false);    setFourStar(false);    setFiveStar(false);}if(rating == 3){    setOneStar(true);    setTwoStar(true);    setThreeStar(true);    setFourStar(false);    setFiveStar(false);}if(rating == 4){    setOneStar(true);    setTwoStar(true);    setThreeStar(true);    setFourStar(true);    setFiveStar(false);}if(rating == 5){    setOneStar(true);    setTwoStar(true);    setThreeStar(true);    setFourStar(true);    setFiveStar(true);}};return (<View style={styles.ratingContainer}><TouchableOpacity onPress={() => setRating(1)}>        {oneStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(2)}>        {twoStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(3)}>        {threeStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(4)}>        {fourStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(5)}>        {fiveStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity></View>);};

How can I upgrade the Typescript version used by React Native?

$
0
0

I'm using import type declarations in my React Native code, which works fine with npx tsc and inside of VS Code. But when I run the app, I get Unexpected Token errors.

How can I get React Native to play nicely with import type? It seems to me it must be using an old version of TypeScript but if I knew how to configure that, I don't recall how now.

(I've tried resetting cache, deleting app from simulator and reinstalling, cleaning Xcode build.)

Edit: I'm thinking this may have to do with an old version of @babel/plugin-transform-typescript, which is part of metro-react-native-babel-transformer, which is required by RN's package.json.

enter image description here

React Native map axios instead of a imported file

$
0
0

I am studying React Native, and I forked this Github Repository and I have a feed.tsx that returns a FlatList and it renders a function that map the variable twitts. I want to try to use Axios instead of data imported file as the following code:

  feed.tsx  import React from 'react';  import {FlatList, View, StyleSheet} from 'react-native';  import {StackNavigationProp} from '@react-navigation/stack';  import {useTheme} from 'react-native-paper';  import axios from 'axios';  import {Twitt} from './components/twitt';  import {twitts} from './data';  import {StackNavigatorParamlist} from './types';  type TwittProps = React.ComponentProps<typeof Twitt>;  function renderItem({item}: { item: TwittProps }) {      return <Twitt {...item} />;  }  function keyExtractor(item: TwittProps) {      return item.id.toString();  }  type Props = {      navigation?: StackNavigationProp<StackNavigatorParamlist>;  };  export const Feed = (props: Props) => {      const theme = useTheme();      var response = axios.get('https://api.themoviedb.org/3/movie/popular?api_key=49f0f29739e21ecda580cd926a19075e&language=en-US&page=1');      const data = response.data.result.map(twittProps => ({          ...twittProps,          onPress: () =>              props.navigation &&              props.navigation.push('Details', {                  ...twittProps,              }),      }));      return (<FlatList              contentContainerStyle={{backgroundColor: theme.colors.background}}              style={{backgroundColor: theme.colors.background}}              data={data}              renderItem={renderItem}              keyExtractor={keyExtractor}              ItemSeparatorComponent={() => (<View style={{height: StyleSheet.hairlineWidth}}/>              )}          />      );  };

And the following twitt.tsx:

      import React from 'react';  import {StyleSheet, View, Image, TouchableOpacity} from 'react-native';  import {      Surface,      Title,      Caption,      Text,      Avatar,      TouchableRipple,      useTheme,  } from 'react-native-paper';  import {MaterialCommunityIcons} from '@expo/vector-icons';  import color from 'color';  type Props = {      id: number;      adult: boolean,      popularity: number,      vote_count: number,      video: boolean,      poster_path: string,      backdrop_path: string,      original_language: string,      original_title: string,      genre_ids: any,      title: string,      vote_average: number,      overview: string,      release_date: string,      onPress: (id: number) => void;  };  export const Twitt = (props: Props) => {      const theme = useTheme();      const iconColor = color(theme.colors.text)          .alpha(0.54)          .rgb()          .string();      const contentColor = color(theme.colors.text)          .alpha(0.8)          .rgb()          .string();      const imageBorderColor = color(theme.colors.text)          .alpha(0.15)          .rgb()          .string();      return (<TouchableRipple onPress={() => props.onPress(props.id)}><Surface style={styles.container}><View style={styles.leftColumn}><Image style={styles.movieImg} source={{uri: "https://image.tmdb.org/t/p/w500/" +props.backdrop_path }}/></View><View style={styles.rightColumn}><View style={styles.topRow}><Title>{props.title}</Title><Caption style={[styles.handle, styles.dot]}>{'\u2B24'}</Caption></View><Text style={{color: contentColor}}>{props.overview}</Text><View style={styles.bottomRow}><View style={styles.iconContainer}><MaterialCommunityIcons                                  name="star-circle"                                  size={20}                                  color={iconColor}                              /><Caption style={styles.iconDescription}>                                  {props.vote_average}</Caption></View><View style={styles.iconContainer}><MaterialCommunityIcons                                  name="thumb-up-outline"                                  size={20}                                  color={iconColor}                              /><Caption style={styles.iconDescription}>                                  {props.popularity}</Caption></View><View style={styles.iconContainer}><MaterialCommunityIcons                                  name="calendar"                                  size={20}                                  color={iconColor}                              /><Caption style={styles.iconDescription}>{props.release_date}</Caption></View></View></View></Surface></TouchableRipple>      );  };  const styles = StyleSheet.create({      container: {          flexDirection: 'row',          paddingTop: 15,          paddingRight: 15,      },      leftColumn: {          width: 100,          alignItems: 'center',          padding: 10      },      rightColumn: {          flex: 1,      },      topRow: {          flexDirection: 'row',          alignItems: 'baseline',      },      handle: {          marginRight: 3,      },      dot: {          fontSize: 3,      },      image: {          borderWidth: StyleSheet.hairlineWidth,          marginTop: 10,          borderRadius: 20,          width: '100%',          height: 150,      },      bottomRow: {          paddingVertical: 10,          flexDirection: 'row',          alignItems: 'center',          justifyContent: 'space-between',      },      iconContainer: {          flexDirection: 'row',          alignItems: 'center',      },      iconDescription: {          marginLeft: 2,          lineHeight: 20,          fontSize: 15      },      movieImg: {          width: "100%",          height: 100,      }  });

But, when I map Axios response data it doesn't work:The same code showing error

pass multiple optional styles into a component

$
0
0

I have a component that looks like this:

type VehicleContainerProps = {  //vehicles: Vehicle[];  vehicles: any[];  //styles?};export const VehicleContainer: React.FunctionComponent<VehicleContainerProps> = ({  vehicles,}) => {  return (<View>      {vehicles.map((item: Vehicle) => (<View style={styles.container} key={item.id}><Thumbnail            style={styles.thumbnail}            source={{              uri:'https://cdn2.iconfinder.com/data/icons/circle-icons-1/64/car-512.png',            }}></Thumbnail><View style={styles.carDetails}><Text style={styles.carModel}>Volkswagen Golf 8</Text></View></View>      ))}</View>  );};export const styles = StyleSheet.create({  container: {    paddingTop: 20,    paddingRight: moderateScale(25),    paddingLeft: moderateScale(25),    flexDirection: 'row',  },)}

usually when I use this component, I don't need to add styles. However, in one particular case, I want to change the styling. Is there any way I can pass multiple styles together such that whichever new styles are provided (eg carModel, thumbnail) etc are used. While for those which have no new styles, the old normal ones should be used.

I passed additional styles like this:

tripVehicleStyles?: any;
export const VehicleContainer: React.FunctionComponent<VehicleContainerProps> = ({  vehicles,  tripVehicleStyles,}) => {

and used them like this:

 style={[styles.thumbnail, tripVehicleStyles.thumbnail]}

Such that if If I pass tripVehicleStyles, they are applied. However, on the screens where I do not pass tripVehicleStyles, I get an error because they are undefined. Even though I am using a question mark in the props.

How can I make this parameter optional? The first style in the array should work if the second is not given

Transform React Native export file in Typescript

$
0
0

How can I translate this .js file into a Typescript one?

import * as Colors from './colors';import * as Spacing from './spacing';import * as Typography from './typography';import * as Mixins from './mixins';export { Typography, Spacing, Colors, Mixins };

Thank you

Edit 1:I'm trying to fix the folowing error:

Cannot find module '_styles' or its corresponding type declarations.

When trying to import a file in another file

import {Colors,Typography,Mixins} from '_styles';

It works, but shows the above warning.I have a setup that allow my to import the file without the complete path that works well but with typescript, it shows a warning.

Edit 2:

I have the following setup in .babelrc

    {"plugins": [    ["module-resolver",      {"cwd": "babelrc","root": ["./src"],"extensions": [".js", ".ios.js", ".android.js", ".ts", ".tsx", ".json"],"alias": {"_assets": "./src/assets","_components": "./src/components","_atoms": "./src/components/atoms","_molecules": "./src/components/molecules","_organisms": "./src/components/organisms","_navigations": "./src/navigations","_scenes": "./src/scenes","_services": "./src/services","_styles": "./src/styles","_utils": "./src/utils","_i18n": "./src/i18n"        }      }    ]  ]}

Using Animated Value in React Native Typescript

$
0
0

I'm trying to write a react native component in typescript that has a Animated.View from the Animated API in the render function.

I'm having an issue setting the Animated.Value as a property of the React Component.

My current code is as follows:

interface NotificationProps {animation : Animated.Value...}class Notification extends React.Component <NotificationProps,NotificationState> {  constructor (props: NotificationProps) {      super(props)      this.props.animation = new Animated.Value(0)      ...      this.state = {...}

However, the ts linter produces the error:

Cannot assign to 'animation' because it is a read-only property

In javascript, simply declaring the Animated.Value in the constructor as below works fine:

this.animation = new Animated.Value(0)

I'm using react native v. 0.61.5

Set stack navigator initialRouteName based on tab

$
0
0

I have a the following Tab Navigator

export const MainNavigator = () => {  return (<Tab.Navigator><Tab.Screen name="Home" options={{ title: "Home" }} component={MainStackScreen} /><Tab.Screen name="Favorite" options={{ title: "Favorite" }} component={MainStackScreen} /></Tab.Navigator>  );};

Where the (simplified) MainStackScreen looks like this:

export const MainStackScreen = () => {  return (<Stack.Navigator screenOptions={{ headerBackTitleVisible: false }}><Stack.Screen name="Home" component={HomeScreen} /><Stack.Screen name="Favorite" component={FavoriteHomeScreen} /><Stack.Screen name="Organisation" component={OrganisationScreen}/><Stack.Screen name="Leagues" component={LeaguesScreen}/><Stack.Screen name="Groupes" component={GroupesScreen}/></Stack.Navigator>  );};

Basically I would like to have a different <Stack.Navigator> initialRouteName depending on which tab is selected.

To give more context, the favorite tab allows user to skip some navigation steps you have on Home tab but let the user navigates threw the same screens. This is why these two tabs share the same stack.


Testing React Native Firebase/Firestore + Typescript with jest on windows machine

$
0
0

I'm trying to write tests for my react native firebase/firestore methods, which are written with jest and typescript. I'm getting different kinds of errors with different approaches, which have led me to follow a ts-jest guide to set up with react native, which led me through an error saying I couldn't use imports (fixed by adding the relevant node_modules to transformIgnorePatterns in jest.config.js), and now I have the error "Invariant Violation: Native module cannot be null".

I also tried setting automock:true in jest.config.js, but this gave me 'Cannot read TypeError: Cannot read property 'OS' of undefined', where undefined is Platform inside @react-native-firebase/app. Does this mean I cannot test these functions on a normal windows machine, and instead need to be running the tests in some ios emulator? I've just migrated from MongoDB+my own server code to using firebase directly from react native in the hopes of avoiding a separate backend for just transporting data from the DB.

In some solutions, I've seen people mocking the functions in /firestore, but I want to actually store data on the emulator running on my machine to actually see if these functions are working. Does anyone have a solution to this? There has to be a lot of people who have had the same issue, but I can't find any solutions for it, so any help would be greatly appreciated.

Here are my current relevant files, tell me if you need more:

package.json:

{"name": "somename","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","emulators:start:firestore": "firebase emulators:start --only firestore","test": "jest",  },"dependencies": {    //Lots of other stuff here, but this is the important one"@react-native-firebase/firestore": "^7.2.2"  },"devDependencies": {"@babel/core": "^7.10.5","@babel/plugin-transform-runtime": "^7.10.5","@babel/runtime": "^7.10.5","@firebase/testing": "^0.20.7","@react-native-community/eslint-config": "^0.0.5","@types/jest": "^26.0.4","@types/react-native": "^0.60.25","@typescript-eslint/eslint-plugin": "^2.12.0","@typescript-eslint/parser": "^2.12.0","babel-jest": "^26.1.0","eslint": "^6.5.1","jest": "^26.1.0","metro-react-native-babel-preset": "^0.56.0","react-test-renderer": "16.9.0","ts-jest": "^26.1.3","typescript": "^3.7.3"  }}

jest.config.js (notice my transformIgnorePattern to ensure the firebase node_modules are compiled correctly):

const { defaults: tsjPreset } = require('ts-jest/presets');module.exports = {  ...tsjPreset,  preset: 'react-native',  transform: {    ...tsjPreset.transform,'\\.js$': './node_modules/react-native/jest/preprocessor.js',  },  transformIgnorePatterns: ["node_modules/?!(@react-native-firebase/firestore|@firebase/testing|@react-native-firebase/app)"],  globals: {'ts-jest': {      babelConfig: true,    }  },  cacheDirectory: '.jest/cache',};

babel.config.js:

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

My testfile:

import * as Members from '../../DBCommunications/MemberService';import firebase, {assertSucceeds} from '@firebase/testing';const memberId = '123';const memberName = 'Test';const memberImage = 'image.png';beforeAll(() => {    firebase.initializeTestApp({projectId: 'testid', auth: {uid: 'tester', email: 'test@test.com'}})});afterAll(async () => {    await Promise.all(firebase.apps().map((app: any) => app.delete()));    await firebase.clearFirestoreData({projectId: 'testid'});});describe('Member Service', () => {    it('Can create a member', async () => {        const member = await Members.createMember(memberId, memberName, memberImage);        expect(member).toBe(true);        expect(true).toBeTruthy();    });});

Members.createMember (important bits):

import firestore, {FirebaseFirestoreTypes} from '@react-native-firebase/firestore'import {Member} from "../Interfaces/Member";export const createMember = async (id: string, name: string, image: string): Promise<boolean> => {    return new Promise<boolean>((resolve, reject) => {        const member: Member = {            id: id,            name: name,            image: image        };        firestore().collection(membersCollectionName).add(member)            .then(() => resolve(true))            .catch(() => reject('Could not create member'));    })};

React list only shows 1 item from loop

$
0
0

Please advice me as my react native page does not loop through all the returned items from the api.

I have checked all i can check but unfortunately, i am unable to find out where the error comes form

I have tested the api with data all seems to be working wellI have also added the styles and json response

json response is

"data":["aaaaaaaaaaaaaaaaaa","{\"amount\": \"2000\", \"dataSource\": null, \"showDatePicker\": false, \"thedatetime\": 2020-07-18T10:49:41.479Z, \"title\": \"Gas\"}"]}aaaaaaaaaaaaaaaaaa Object {"amount": "2000","dataSource": null,"showDatePicker": false,"thedatetime": 2020-07-18T10:49:41.479Z,"title": "Gas",}Unrecognized event: {"type":"client_log","level":"log","data":["aaaaaaaaaaaaaaaaaa","{\"amount\": \"10000\", \"dataSource\": null, \"showDatePicker\": false, \"thedatetime\": 2020-07-18T10:49:41.479Z, \"title\": \"Food\"}"]}aaaaaaaaaaaaaaaaaa Object {"amount": "10000","dataSource": null,"showDatePicker": false,"thedatetime": 2020-07-18T10:49:41.479Z,"title": "Food",}

See my code below

import React, { Component } from "react";import {  FlatList,  Text,  View,  StyleSheet,  ActivityIndicator} from "react-native";import Constants from "expo-constants";function Item({ title }) {  return (<View style={styles.item}><Text style={styles.title}>{title}</Text></View>  );}class ExpenseList extends Component {  constructor(props) {    super(props);    this.state = {      isLoading: true,      dataSource: null    };  }  componentDidMount() {    return fetch("https://myurl.com/expense/api/get_all.php")      .then(response => response.json())      .then(responseJson => {        this.setState({          isLoading: false,          dataSource: responseJson.users        });      })      .catch(error => console.log(error));  }  render() {    if (this.state.isLoading) {      return (<View style={styles.container}><ActivityIndicator /></View>      );    } else {      let myExpenses = this.state.dataSource.map((val, key) => {        return (<View key={key} style={styles.item}><Text>{val.title}</Text><Text>{val.title}</Text></View>        );      });      return <View style={styles.container}>{myExpenses}</View>;    }  }}    const styles = StyleSheet.create({  container: {    flex: 1,    marginTop: Constants.statusBarHeight  },  item: {    backgroundColor: "#f9c2ff",    padding: 10,    marginVertical: 4,    marginHorizontal: 8  },  title: {    fontSize: 16  }});export default ExpenseList;

Unable to install React Native Maps

$
0
0

I am studying and developing a React native project using Expo, when trying to install React Native Maps( command expo install react-native-maps) the error below occurs:

https://i.stack.imgur.com/QP3i1.png

Due to this problem I went in search of other alternatives to install the package, and used the command "npm install react-native-maps --save-exact" the installation was successful ,however when running the command "npm audit fix" I was informed that the package "undefined@react-native/maps" was not installed .

In order to solve this error a tried install this package using the command "npm install undefined@react-native/maps" and the erro below occurs:

https://i.stack.imgur.com/C3AW5.png

React Native header bar

$
0
0

How can I configure the Android header bar background color similar to the ios with react native?

enter image description here

Thanks

React native, entered Form values are passed as null from react native Fetch method

$
0
0

Please advise me as my react native page does not add all the state items from into the add api

the api is working

I have checked all I can check but unfortunately, I am unable to find out where the error comes formhttpsI have tested the API with data all seems to be working well I have also added the styles and see the code below

import React, { Component } from "react";import { useState } from "react";import {  TouchableHighlight,  View,  TextInput,  StyleSheet,  KeyboardAvoidingView,  Picker,  Button,  Alert,  Text} from "react-native";import DateTimePicker from "react-native-modal-datetime-picker";import { formatDateTime } from "./utilities";const createStartedAddingAlert = () =>  Alert.alert("Started Adding","Succesfully started Adding",    [      {        text: "Cancel",        onPress: () => console.log("Cancel Pressed"),        style: "cancel"      },      {        text: "OK",        onPress: () => console.log("ssssssssssssssssssss started adding>>>>>> ")      }    ],    { cancelable: false }  );const createFinishedAddingAlert = () =>  Alert.alert("Finished Adding","Succesfully finished Adding",    [      {        text: "Cancel",        onPress: () => console.log("Cancel Pressed"),        style: "cancel"      },      {        text: "OK",        onPress: () => console.log("ffffffffffffffff finished adding>>>>>> ")      }    ],    { cancelable: false }  );class ExpenseForm extends Component {  constructor(props) {    super(props);    this.state = {      dataSource: null    };  }  state = {    title: null,    description: null,    category: "",    subcategory: "",    thedatetime: "",    amount: 0  };  state = {    category: "--Select One--"  };  handleAddPress = () => {    console.log("aaaaaaaaaaaaaaaaaa", this.state);    createStartedAddingAlert();    return fetch("https://example.com/expense/api/add_exp.php", {      method: "POST",      headers: {        Accept: "application/json","Content-Type": "application/json"      },      body: JSON.stringify({        user_id: "default",        title: this.state.title,        amount: this.state.amount,        description: "",        category: this.state.category,        subcategory: "",        date_time: formatDateTime(this.state.thedatetime)      })    })      .then(response => response.json())      .then(responseJson => {        this.setState({          isLoading: false,          dataSource: responseJson.response_code        });      }, console.log("dataSource is >> " + this.state.dataSource))      .catch(error => console.log(error));    createFinishedAddingAlert();  };  handleChangeTitle = value => {    this.setState({ title: value });  };  handleChangeAmount = value => {    this.setState({ amount: value });  };  handleDatePicked = thedatetime => {    this.setState({      thedatetime    });    this.handleDatePickerHide();  };  handleDatePickerHide = () => {    this.setState({      showDatePicker: false    });  };  handleDatePress = () => {    this.setState({      showDatePicker: true    });  };  render() {    return (<View        style={{          flex: 1        }}><KeyboardAvoidingView          behavior={Platform.OS == "ios" ? "padding" : "height"}          style={styles.container}><View style={styles.fieldContainer}><TextInput              style={styles.text}              placeholder="Expense Title"              spellCheck={false}              value={this.state.title}              onChangeText={this.handleChangeTitle}            /></View><View style={styles.fieldContainer}><TextInput              style={styles.text}              placeholder="Amount"              spellCheck={false}              value={this.state.amount}              keyboardType={"numeric"}              onChangeText={this.handleChangeAmount}            /></View><View style={styles.fieldContainer}><TextInput              style={[styles.text, styles.borderTop]}              placeholder="Event date"              spellCheck={false}              editable={!this.state.showDatePicker}              onFocus={this.handleDatePress}              value={formatDateTime(this.state.thedatetime)}            /><DateTimePicker              isVisible={this.state.showDatePicker}              mode="datetime"              onConfirm={this.handleDatePicked}              onCancel={this.handleDatePickerHide}            /></View><View style={styles.pickerContainer}><Picker              selectedValue={this.state.category}              style={{ height: 50, width: 200 }}              onValueChange={(itemValue, itemIndex) =>                this.setState({ category: itemValue })              }><Picker.Item label="--Select One--" value="--Select One--" /><Picker.Item label="Automobile" value="Automobile" /><Picker.Item label="Clothing" value="Clothing" /><Picker.Item label="Debt Reduction" value="Debt Reduction" /><Picker.Item label="Education" value="Education" /><Picker.Item                label="Entertainment/Fun"                value="Entertainment/Fun"              /><Picker.Item label="Family" value="Family" /><Picker.Item label="Food" value="Food" /><Picker.Item label="Gifts" value="Gifts" /><Picker.Item label="Giving" value="Giving" /><Picker.Item                label="Household Items/Supplies"                value="Household Items/Supplies"              /><Picker.Item label="Insurance" value="Insurance" /><Picker.Item label="Investments" value="Investments" /><Picker.Item label="Maintenance" value="Maintenance" /><Picker.Item label="Medical" value="Medical" /><Picker.Item label="Personal" value="Personal" /><Picker.Item label="Shelter/Home" value="Shelter/Home" /><Picker.Item label="Training" value="Training" /><Picker.Item label="Transportation" value="Transportation" /><Picker.Item label="Travel/Vacations" value="Travel/Vacations" /><Picker.Item label="Utilities" value="Utilities" /></Picker></View><TouchableHighlight            onPress={this.handleAddPress}            style={styles.button}><Text style={styles.buttonText}>Add</Text></TouchableHighlight></KeyboardAvoidingView></View>    );  }}const styles = StyleSheet.create({  fieldContainer: {    marginTop: 20,    marginLeft: 20,    marginRight: 20,    backgroundColor: "#fff"  },  text: {    height: 40,    margin: 0,    marginRight: 7,    paddingLeft: 10  },  borderTop: {    borderColor: "#edeeef",    borderTopWidth: 0.5  },  button: {    height: 50,    backgroundColor: "#48BBEC",    borderColor: "#48BBEC",    alignSelf: "stretch",    margin: 10,    justifyContent: "center",    alignItems: "center",    borderRadius: 5  },  buttonText: {    color: "#fff",    fontSize: 18  },  pickerContainer: {    flex: 1,    paddingTop: 5,    alignItems: "center"  }});export default ExpenseForm;

Redux state doesn't update from the first time

$
0
0

Maybe that's a stupid question, but I have a problem. My state looks like this:

const initialState: PhotoState = {  photos: [],};

The reducer code looks like this:

const initialState: PhotoState = {  photos: [],};export default function photoReducer(state = initialState, action: PhotoActionTypes): PhotoState {  switch (action.type) {    case SET_PHOTOS:      const photos: any[] = action.payload;      return {...state, photos};  }  return state;};

I get photos from API and then set them this way:

export function setPhotos(payload: any[]): PhotoActionTypes {  return {type: SET_PHOTOS, payload};}export function getPhotos() {  return (dispatch: Dispatch<PhotoActionTypes>, getState: () => RootState): void => {    const profile_id = getState().auth.profile_id;    ax().post('pictures/api/pictures/list', {profile_id}).then((response) => {      const photos: any[] = response.data.pictures || [];      dispatch(setPhotos(photos));    })  }}

Also I have an action that sends a new photo to the server and saves it in history. Then I get photos in component:

useEffect(() => {    dispatch(getPhotos());  }, []);const handleSendPhoto = (): void => {    dispatch(sendPhoto(image?.base64));    dispatch(getPhotos());  }

The whole component:

const PhotoScreen = () => {  const [photoFlag, setPhotoFlag] = useState(false);  const [image, setImage] = useState<TakePictureResponse | null>(null);  const [height, setHeight] = useState(0);  const width = Dimensions.get('screen').width / 5;  const dispatch = useDispatch();  const handleSendPhoto = (): void => {    dispatch(sendPhoto(image?.base64, location));    dispatch(getPhotos());  }  const PhotoView = () => (<View><FastImage        style={{width: width, height: height}}        source={{          uri: `data:image/jpeg;base64, ${image?.base64}`,          priority: FastImage.priority.normal,        }}        resizeMode={FastImage.resizeMode.contain}        onLoad={evt => {          setHeight(evt.nativeEvent.height / evt.nativeEvent.width * width)        }}      /><Button        mode="contained"        onPress={handleSendPhoto}        disabled={!image}        color={constants.buttonColor}>        Add photo</Button></View>  );  return (<SafeAreaView style={{...mainStyles.screen, ...styles.container}}><StatusBarDark />      {!photoFlag && (<View><Button          mode="contained"          onPress={() => setPhotoFlag(true)}          color={constants.buttonColor}>          Make photo</Button></View>)}      {photoFlag && <CameraComponent setImage={setImage} setPhotoFlag={setPhotoFlag}/>}      {image !== null && <PhotoView />}</SafeAreaView>  );};export default PhotoScreen;

But state updates only from the second time. I press the button 'Add photo', photo appends to history, but doesn't shows up in it. Then I press the button again, and previous photo shows up in history, but current photo doesn't.

How can I fix it?

UPD: Problem was solved. The question may be closed.

FlatList scrollToIndex typescript expo

$
0
0

I'm trying to set up scroll to index on a flatList based a variable with typescript.Examples I've found are with react and doesn't seem to work with what I have at the moment.

My project actually has two flatlists and I want the scroll to dynamically move based on what is selected.Below is a simplified example of what I have, just want an idea on how to make it work first. But obviously not working.

<FlatList      //tried this, but don't know how to pass the actual index      ref={(ref) => { ref?.scrollToIndex({index: 0}) }}      renderItem={({ item }) => {        return (<TouchableOpacity            onPress={() => onSelect(item, index)}> <View></View></TouchableOpacity>      )}}    />

onSelect function, dont know how to pass the index back to the flatList

const onSelect = (item, index) => {  //scrollToIndex(index)?}

Some guidance would be appriciated :)


T extends ChangeEvent ? void : (e: string | ChangeEvent)

$
0
0

I am using a custom formik component like this in my screens:

<Formik                initialValues={initialValues}                onSubmit={handleSubmitForm}                validationSchema={validationSchema}>                {({ handleChange, handleBlur, handleSubmit, values }) => (<View style={styles.searchFieldContainer}><View style={styles.form}><FieldInput                        handleChange={handleChange}                        handleBlur={handleBlur}                        value={values.phoneNumber}                        fieldType="phoneNumber"                        icon='phone'                        placeholderText='49152901820'                      /><ErrorMessage                        name="phoneNumber"                        render={(msg) => (<Text style={styles.errorText}>{msg}</Text>                        )}                      /></View><View style={styles.buttonContainer}><Button                        onPress={handleSubmit}>                        Search</Button></View></View>                )}</Formik>

I get a TypeScript error on handleChange and handleBlur that:

Type '{ (e: ChangeEvent<any>): void; <T = string | ChangeEvent<any>>(field: T): T extends ChangeEvent<any> ? void : (e: string | ChangeEvent<any>) => void; }' is not assignable to type '(e: string) => undefined'.  Types of parameters 'e' and 'e' are incompatible.    Type 'string' is not assignable to type 'ChangeEvent<any>'FieldInput.tsx(9, 3): The expected type comes from property 'handleChange' which is declared here on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'

The field inputs are supposed to be strings and I don't think I should change ChangeEvent's type to string. 'any' is also not a good option. How can I fix this?

How is React Native multiple data input?

$
0
0

My English is not very good, sorry for that. There is a structure that I want to make multiple data entries. I will add separate json lines for each input. But I can add once from the same line. But I want to create a separate json data for each input. I am sharing the sample code. It doesn't work that way because it constantly updates the previous data in.

var families = [];for(let i = 0; i < formStep + 1; i++) {    families.push(<View key={i}><View><Text style={{ marginBottom: 5 }}>T.C</Text><Input                    placeholder='Lütfen T.C belirtin'                    style={{ marginBottom: 10 }}                                                onChangeText={(input) => this.setState(prevState => ({                                                  formData: [...prevState.formData, {tc: input}]                    }))}                /></View><View><Text style={{ marginBottom: 5 }}>İsim</Text><Input                    placeholder='Lütfen ad ve soyad belirtin'                    style={{ marginBottom: 10 }}                /></View><View><Text style={{ marginBottom: 5 }}>Meslek</Text><Input                    placeholder='Lütfen meslek belirtin'                    style={{ marginBottom: 10 }}                /></View>            {(formStep > 0) ? <Divider style={{marginBottom: 15, marginTop: 10}}></Divider> : null}</View>    )}

working input onChangeText method;

Array [  Object {"tc": "0",  },]Array [  Object {"tc": "0",  },  Object {"tc": "00",  },]Array [  Object {"tc": "0",  },  Object {"tc": "00",  },  Object {"tc": "000",  },]

But I want;

Array [  Object {"tc": "000",  },]

And then if there is more than one input;

Array [  Object {"tc": "000",  },  Object {"tc": "111",  },  Object {"tc": "222",  },]

I hope I could tell. Thanks for your help in advance.

React Navigation route.params typescript

$
0
0

I'm creating a Expo managed React Native app with TypeScript and having some problems with React Navigation and TypeScript.

I want to specify the icon for the Bottom Tab Navigator on the Tab.Screen component.

This code works but complains because route.params could be undefined (line 10).

Property 'icon' does not exist on type 'object'

Can I make the icon prop required on initialParams?

I have looked in the documentation without any luck.

const App: React.FC<{}> = () => {  return (<SafeAreaView style={styles.container}><NavigationContainer><Tab.Navigator          screenOptions={({ route }) => ({            tabBarIcon: ({ size, color }) => (<MaterialIcons                size={size}/* ===> */      name={route.params.icon}                color={color}              />            ),          })}><Tab.Screen            name="EventListView"            initialParams={{ icon: 'view-agenda' }}            component={EventListScreen}          /><Tab.Screen            name="CreateEvent"            initialParams={{ icon: 'public' }}            component={SettingsScreen}          /></Tab.Navigator></NavigationContainer></SafeAreaView>  )}

Using OR operator in React js conditional rendering

$
0
0

I want to conditionally render a button based on two conditions.Am not really sure if am doing it the right way.

But i get this error This condition will always return 'true' since the types '"started"' and '"cancelled"' have no overlap.ts(2367) where the red underline is.

Am using React js with typescriptenter image description here

Webview iframe doesn't work, it doesn't appear on the screen

$
0
0

I need to insert video in my app. I use WebView to insert iframe, but it doesn't work.

const Course = () => {  const route = useRoute();  const course = useSelector((state: RootState) => state.profile.course);  const dispatch = useDispatch();  const {id}: any = route.params;  useEffect(() => {    dispatch(getCourse(id))  }, []);  return (<SafeAreaView><View><TextHeader>{course?.title}</TextHeader><WebView           style={{width: course?.frame_width, height: course?.frame_heigth}}          source={{uri: course?.video}}        /></View></SafeAreaView>  );};

Why does it happen? And how can I fix it?

Viewing all 6215 articles
Browse latest View live


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