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

How to change main image slider using thumbnail image on click in react native?

$
0
0

I had Created an E-commerce app like Flipkart moreover I have to create the product image. Whenever I click on the bottom thumbnail image the main image needs to be changed dynamically. I have attached the screenshot here for the reference.

Screnshot reference


Getting "Invalid call" when using require with Typescript and Expo

$
0
0

I am trying to play some audio in a react-native app created with the expo-cli.

The code is written in typescript and the offending code looks like this, taken from the expo.io documentation:

import * as React from 'react'import { WorkoutComponent } from "./WorkoutExecutor";import { Audio } from 'expo';export default class AudioPlayer {    private async playAudio(fileName: string) {        console.log("Playing Audio: "+ fileName);        const soundFile = './assets/sounds/'+ fileName +'.mp3';        try {            const { sound: soundObject, status } = await Audio.Sound.createAsync(              require(soundFile),              { shouldPlay: true }            );            // Your sound is playing!          } catch (error) {              console.log(error);            // An error occurred!          }    }[...]}

When the app loads, it gives the following error, even before it gets to the screen with the sound

[...]\src\AudioPlayer.ts:Invalid call at line 13: require(soundFile)

I realize that the coe example is with javascript and not typescript, but what am I missing?

My tsconfig.json is the one from the expo typescript example and looks like this

{"compilerOptions": {"baseUrl": "./src","esModuleInterop": true,"experimentalDecorators": true,"forceConsistentCasingInFileNames": true,"importHelpers": true,"jsx": "react-native","module": "es2015","moduleResolution": "node","noEmitHelpers": true,"noImplicitReturns": true,"noUnusedLocals": true,    // Using the type definitions in @types/expo becuase they are still better than the ones provided by expo. See SvgScreen.tsx and SystemFontsScreen.tsx."paths": {"expo": ["../node_modules/@types/expo","../node_modules/expo"      ],    },"skipLibCheck": true,"strict": true,"target": "es2017"  },"exclude": ["node_modules"  ]}

react native unfocus TextInput

$
0
0

I want to make a search bar in react-native like that :

enter image description here

If I click on icon, I focus on textInput, but if I click on other part of screen, unfocus the textInput.

The focus part is working with the ref, but I don't know if it's possible to unfocus the textinput when I click in other part of the screen.

<TextInput    multiline={false}    onChangeText={(text) => onChangeText(text)}    placeholder="search"    style={styles.textInput}    value={value}    ref={research}></TextInput><TouchableOpacity onPress={()=>research.current.focus()}><Ionicons name="md-search" size={24} ></Ionicons></TouchableOpacity>

How to show multiple components in a specific position inside of a parent component in react-native?

$
0
0

I am trying to render multiple components inside of a parent component on a specific position (based on some calculations). The calculations that give me the vertical position look correct, but the components are not displayed in the position they should. I have tried both absolute window position and relative component position with no luck.

The parent looks like follows:

const top = 170;const bottom = 10;const left = 10;const right = 10;const styles = StyleSheet.create({  grid: {    flex: 1,    position: 'absolute',    top: top,    height: Dimensions.get('window').height - top - bottom,    width: Dimensions.get('window').width - left - right,    borderLeftColor: 'black',    borderLeftWidth: 1,    borderBottomColor: 'black',    borderBottomWidth: 1  }});const DrawGrid: React.FC<IDrawGrid> = ({ maxDistance, elements }) => {  const [gridSize, setGridSize] = useState<LayoutRectangle>();  return (<View style={styles.grid} onLayout={(event) => {      setGridSize(event.nativeEvent.layout);    }}>      {elements.map((element, index) => {        return (<DrawElement element={element} maxDistance={maxDistance} gridSize={gridSize} index={index * 2} />        )      })}</View>  );};

And the child component that renders all the elements looks like follows:

const top = 170;const bottom = 20;const left = 10;const right = 10;const styles = StyleSheet.create({  elementContainer: {    borderLeftColor: 'red',    borderLeftWidth: 1,    borderTopColor: 'red',    borderTopWidth: 1,    borderRightColor: 'red',    borderRightWidth: 1,    borderBottomColor: 'red',    borderBottomWidth: 1,    borderRadius: 5,    padding: 2,    position: 'relative',    alignSelf: 'flex-start'  }});const getVerticalPosition = (someDistance: number, maxDistance: number, height: number) => {  if (!someDistance || !maxDistance) return { top: 0 };  const topDistance = (1 - (someDistance / maxDistance)) * height;  return { top: topDistance };};const DrawElement: React.FC<IDrawElement> = ({ maxDistance, element, gridSize, index }) => {  const styleVertical = getVerticalPosition(someDistance, maxDistance, gridSize.height);  return (<View key={key} style={[styles.elementContainer, styleVertical]}>      {/* <Text>x</Text> */}</View>  );};

I can see how getVerticalPosition returns the right value, but the element is never located in the position expected. It is quite frustrating to see how an element that has top 50 can appear vertically in between two elements that have top 100 and top 80, respectively. My first thought was that I am messing up the styles somehow, I also tried giving a different zindex to each element without luck. Any ideas what could happen? Any help would be much appreciated, thank you!

typescript expo '_this.flatListRef = _ref4' undefined is not an object

$
0
0

Trying to set up scrollToIndex on a flatlist with typescript on expo but getting an error I don't really understand.I was following the example snack https://snack.expo.io/@s2gt05/flatlist-scrolltoindex-practical-example.-

Below is the flatlist that I have now

<FlatList        data={data}        ref={(ref) => {if (ref) {this.flatListRef = ref }}}        renderItem={({ item, index }) => (<TouchableOpacity onPress={() => onSelect(index)}><Text>{item.title}</Text></TouchableOpacity>        )}      />    const categorySelector = (index) => {      if (this.flatListRef) {        this.flatListRef.scrollToIndex({index: index})      }    }

Change language based on user selection on expo

$
0
0

Just wondering if there's any way to change the language of an expo app with typescript based on user selection (so not device language).I read through the docs on expo https://docs.expo.io/versions/latest/sdk/localization/ but there doesn't seem to be anything on it.

Below is what I have currently, and it's only working for device set language.

import * as Localization from 'expo-localization';import I18n from 'i18n-js';// import translationsimport en from './en.json'import zh from './zh.json'// bind translations to i18nI18n.translations = {  en,  zh}// set phones languageconst getLanguage = async() => {  try {    const choice = Localization.locale    I18n.locale = choice.substr(0, 2)    I18n.initAsync()  } catch (error) {    console.log(error)  }}getLanguage()// export functionexport function t(name: string) {  return I18n.t(name)}

Only thing now is that I don't know how to pass a language based on user input.

Changing i18n.local and storing in asyncStorage does not change language of app expo

$
0
0

I'm trying to make a dual language app that allows users to select the language they're after, but when selecting, it doesn't change despite i18n.currentLocale() showing the correct selected language.The language will change if I save something on VS code and fast refresh is on.

Below is the code I have for it. Built on expo with typescript.

This is the i18n config

import i18n from 'i18n-js';import AsyncStorage from '@react-native-community/async-storage'import en from './en.json'import zh from './zh.json'i18n.translations = {  en,  zh}async function getLanguage() {  const choice = await AsyncStorage.getItem('setLanguage')  i18n.locale = choice  i18n.fallbacks = true  console.log(i18n.currentLocale())}getLanguage()export function t(name: string) {  return i18n.t(name)}

Language selector

export default function LanguageChange() {    const onPress = async (language: string) => {        await AsyncStorage.setItem('setLanguage', language).then(()=>{});        Updates.reload();    }  return (<View style={styles.selectLanguageContainer}><TouchableOpacity onPress={() => onPress("en")}><Text>English</Text></TouchableOpacity><TouchableOpacity onPress={() => onPress('zh')}><Text>Chinese</Text></TouchableOpacity></View>  );}

React Native with TypeScript Error unable to resolve module

$
0
0

I just created a new project with React Native Typescript template. But I found that when I import a new component it throws the following error. My new component is located inside src/screens/HomeScreen.tsx

error: Error: Unable to resolve module `src/screens/HomeScreen` from `App.tsx`: src/screens/HomeScreen could not be found within the project.

If I do the same component inline within the App.tsx then it works just fine. But importing from another file causing this issue. I tried to delete and re-create the issue, but still happening.

Can someone help me out on this. Thanks in advance

App.tsx

import React from 'react';import {  SafeAreaView,  StyleSheet,  ScrollView,  View,  Text,  StatusBar,} from 'react-native';import HomeScreen from 'src/screens/HomeScreen';const App = () => {  return (<HomeScreen/>  );};export default App;

HomeScreen.tsx

import React from 'react'import {Text} from 'react-native'const HomeScreen = (): any => {    return (<><Text>test </Text>   </>    )}export default HomeScreen

The folder structure

enter image description here


How to correctly send an image to the backend (nodejs) using multer in React Native

$
0
0

I'm having trouble sending a photo, in a PUT route, be it with Axios or Fetch, anyway, my Nodejs backend is configured and the whole upload process works normal testing by Insonmia, but in React Native It does not work properly.

BACKEND - CONTROLLER FOR UPDATING USER DATA

  async updateUserData(req: Request, res: Response, next: NextFunction) {    const { id } = req.params;    const { username, status } = req.body as IBodyData;    try {      const userExists = await knex('tb_user')        .where('id', Number(id))        .first();      if (!userExists) {        return res.status(400).json({ error: 'User does not exist.' });      }      const serializedUserInfo = {        photo: `${process.env.BASE_URL}/uploads/${req.file.filename}`,        username,        status,      };      const updateInfo = await knex('tb_user')        .update(serializedUserInfo)        .where('id', Number(id));      if (!updateInfo) {        return res.status(400).json({ error: 'Error updating data.' });      }      return res.json(updateInfo);    } catch(err) {      return res.status(500).json({ error: 'Error on updating user.' });    }  }

BACKEND - ROUTE

routes.put('/updateuser/:id',  multer(multerConfig).single('userphoto'),  UserController.updateUserData);

CONFIG MULTER

export default {  fileFilter: (req: Request, file, cb) => {    const allowedMimes = ['image/jpeg','image/jpg','image/pjpeg','image/png',    ];    if (!allowedMimes.includes(file.mimetype)) {      return cb(new Error('Invalid file type.'));    }    return cb(null, true);  },  limits: {    fileSize: 2 * 1024 * 1024,  },  storage: multer.diskStorage({    destination: resolve(__dirname, '..', '..', 'uploads'),    filename: (req: Request, file, cb) => {      const filename = `${randomBytes(6).toString('hex')}-${file.originalname}`;      return cb(null, filename);    }  })} as Options;

REACT NATIVE - FUNCTION FOR GET DATA OF PHOTO AND SET ON STATE

  function handleUploadImage(image: IImagePickerResponse) {    if (image.error) {      return;    }    if (image.didCancel) {      return;    }    if (!image.uri) {      return;    }    setSelectedImage({      fileName: image.fileName,      fileSize: image.fileSize,      type: image.type,      uri: image.uri,    });  }

REACT NATIVE - FUNCTION FOR SEND DATA IN API

  async function handleSaveChange() {    try {      const formData = new FormData();      formData.append('userphoto', {        uri:          Platform.OS === 'android'            ? selectedImage?.uri            : selectedImage?.uri?.replace('file://', ''),        type: selectedImage.type,        name: selectedImage.fileName,      });      formData.append('username', usernameInput);      formData.append('status', statusInput);      console.log(formData);      await api.put(`/updateuser/${userData?.id}`, formData, {        headers: {'Content-Type': 'multipart/form-data',        },      });      // const updateUser = await fetch('http://192.168.2.8:3333/updateuser/1', {      //   method: 'POST',      //   headers: {      //     'Content-Type': 'multipart/form-data',      //   },      //   body: formData,      // })      //   .then((response) => {      //     response.json();      //   })      //   .then((response) => {      //     console.log(response);      //   })      //   .catch((err) => console.log(err));      return Toast.success('Informações alteradas com sucesso.');    } catch (err) {      const {error} = err.response.data;      return Toast.error(error);    }  }

obs: A note to take into account is that in the formData.append ('userphoto', value) part if the value has sent a normal json object, the request is neither made nor the Network Error error even IP address being correct the port too, anyway, and if I use formData.append ('userphoto', JSON.stringfy(value)) the request is made normally but in the backend the photo arrives as undefined and the rest of fields are sent and received normal.

I really tried several things and I couldn't, I changed the type of the PUT method to POST without success, add 'Accept': 'application/json' without success, as I said, the normal sending by Insomnia is working.

Finally, here is the lib configuration I used to get the photo:

REACT NATIVE IMAGE PICKER

ImagePicker.showImagePicker(  {    title: 'Selecione uma imagem',    takePhotoButtonTitle: 'Tirar foto',    chooseFromLibraryButtonTitle: 'Escolher da galeria',    cancelButtonTitle: 'Cancelar',    noData: true,    // storageOptions: {    //   skipBackup: true,    //   path: 'images',    //   cameraRoll: true,    //   waitUntilSaved: true,    // },  },  handleUploadImage,)

SOLVED

Apparently it was a problem with the version of React Native, I am currently using version 0.62.XX

To resolve, just comment line number 43 in the file:

android/app/src/debug/java/com/mobile/ReactNativeFlipper.java

The code is this:

builder.addNetworkInterceptor(new FlipperOkhttpInterceptor (networkFlipperPlugin));

Item of key extractor has type unknown - React Native

$
0
0

How can I define a type for the renderItem handler of a FlatList in React Native?

That's how I'm currently handling it:

// Importing the generic type of the FlatList render item handlerimport { ListRenderItem } from "react-native";// Associating the type to the handler const renderItem: ListRenderItem<Bill> = useCallback(({ item }) => (<BillCard      id={item.id}      name={item.name}      icon={item.icon}{...}return (<List      data={bills}      renderItem={renderItem}      keyExtractor={(item) => String(item.id)}    />  );

But unfortunately, that's not working, refer to the following errors:

enter image description hereenter image description here

React Native Typescript Formik cast event type

$
0
0

In the Formik documentation for React Native it has an example form:

<Formik initialValues={{ email: '' }} onSubmit={(values) => console.log(values)}>  {({ handleChange, handleBlur, handleSubmit, values }) => (<View><TextInput onChangeText={handleChange('email')} onBlur={handleBlur('email')} value={values.email} /><Button onPress={handleSubmit} title="Submit" /></View>  )}</Formik>

This, however, gives me a Typescript error:

No overload matches this call.Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.  Type '(e?: FormEvent<HTMLFormElement> | undefined) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.    Types of parameters 'e' and 'ev' are incompatible.      Type 'NativeSyntheticEvent<NativeTouchEvent>' is not assignable to type 'FormEvent<HTMLFormElement>'.

Given that I am getting the handleSubmit function from destructuring, how can I cast the type of event correctly?

Note: I know I can do this, but I have read that this will cause additional renders in React:

<Button onPress={(e) => handleSubmit(e as any)} title="Submit" />

How to import a markdown file in a typescript react-native project?

$
0
0

I have tried to import a markdown file into my typescript react-native project in 2 ways.

import * as readme from "./sample.md"
import readme from "./sample.md"

Both didn't work. So I found a similar issue reported previously and mentioned about making a typings.d.ts file for declaring modules, and i've tried this as well but it still doesn't work.

declare module "*!txt" {    const value: any;    export default value;}declare module "*.md" {    const value: any;    export default value;}

EDIT:There is no import error on Vscode but on the react-native app itself, it says that it cannot find module './sample.md' as it is only looking for (.native|.ios|.json|.ts etc) files.

Any help would be appreciated, been stuck on this for far too long.Thank you!

sound.stop() does not work , but sound.play() is working in Howlerjs?

$
0
0

I am trying to use Howler.js in Reactjs using typescript.

I can able to play the sound but it does not pause or stop. Here is my code.

This a component where I am passing all the audio details using props.I did console.log() to check, is it going in else part and it goes and print the console.Please help me in this

import React, { useState } from 'react';import Button from 'components/button/button';import PlayIcon from 'assets/icons/play.svg';import PauseIcon from 'assets/icons/pause.svg';import AudioWave from 'assets/icons/sound-wave.svg';import { Howl, Howler } from 'howler';   interface Props {    name?: string,    audio?: any,    loop?: boolean,    autoplay?: boolean}const Audio = (props: Props) => {    const { name, audio, loop, autoplay } = props;    const [isPlaying, setIsPlaying] = useState(false);    const [audioId, setAudioId] = useState(0);    const sound = new Howl({        src: [audio],        autoplay: autoplay,        loop: loop,        volume: 1,        onend: function () {            setIsPlaying(false);        },    });    Howler.volume(0.5);    const playAudio = () => {        let Id: any;        if (!isPlaying) {            Id = sound.play();            setAudioId(Id);            setIsPlaying(true);            console.log('THS')        } else {            sound.stop(audioId);            console.log('THATAT', audioId)        }        console.log(sound)    }    return (<div className="flex flex-col items-center justify-center rounded shadow-md w-full">            {console.log(isPlaying, audioId)}<div className="grid grid-cols-12 w-full"><div className="col-span-6 p-2"><p className="text-left">                        {name}</p></div><div className="col-span-6 p-2"><p className="text-right text-light-gray">                        {sound ? `${Duration.toTimeFormat(sound._duration * 1000)}s` : '0:00s'}</p></div></div><div className="grid grid-cols-12 w-full items-center justify-center"><div className="grid col-span-2 w-full p-2"><img                        className="w-full cursor"                        onClick={() => playAudio()}                        src={isPlaying ? PauseIcon : PlayIcon}                        alt="PlayPauseIcon"                    /></div><div className="grid col-span-10 p-2"><img className="w-full" alt="Audio Wave" src={AudioWave} /></div></div></div>    )}export default Audio;

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

$
0
0

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

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

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

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

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

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

Nativebase React Native why can't i pass a number on an input

$
0
0

I'm using react native nativebase and i want to pass a number to my input value but im getting an error that says i cannot pass a number to a string.

<Input          keyboardType="numeric"          onChangeText={(text) => setTarget(text)}          value={target}        />

Now if I do this.

<Input          keyboardType="numeric"          // onChangeText={(text) => setTarget(text)}          value={"target"}

The error disappear.This is the definition of the value

const [target, setTarget] = useState<number>(0);

enter image description here


React Native is Not fetching the latest data from API call

$
0
0

I sicerely Apologies if this has been asked before. I am a bit new to react native and react in general.

my react nativee code is not fetcing the latest datasee the code for the list component belowI would deeply appreciate it if you can tell me why this is happening and how to make it pick the latest data

import React, { Component } from "react";import {  FlatList,  Text,  View,  StyleSheet,  ScrollView,  ActivityIndicator} from "react-native";import Constants from "expo-constants";import { createStackNavigator } from "@react-navigation/stack";import { toCommaAmount } from "./utilities";const Stack = createStackNavigator();function MyStack() {  return (<Stack.Navigator><Stack.Screen name="Home" component={ExpenseList} /><Stack.Screen name="NewTransaction" component={ExpenseForm} /></Stack.Navigator>  );}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://example.com/expense/api/get_all.php")      .then(response => response.json())      .then(responseJson => {        this.setState({          isLoading: false,          dataSource: responseJson.items        });      })      .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} {toCommaAmount(val.amount)}</Text><Text>{val.date_time}</Text></View>        );      });      return <View style={styles.container}>{myExpenses}</View>;    }  }}export default ExpenseList;

Type 'Element | undefined' is not assignable to type 'ReactElement

$
0
0

I have a component that looks like this. This version works perfectly:

export default function StatusMessage(isAdded: boolean, errorMessage: string) {  if (isAdded) {    return <ResultAlert severity="success" text="User Added" />;  } else {    if (errorMessage !== '') {      if (        errorMessage.includes('email')      ) {        return <ResultAlert severity="error" />;      }      if (        errorMessage.includes('phone number')      ) {        return (<ResultAlert severity="error" text="" />        );      }     }  }}

Now, I am trying to change the way I export it. I am trying this:

type StatusMessageProps = {  isAdded: boolean;   errorMessage: string;}export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({  isAdded,  errorMessage}) => {

but i keep getting an error that:

Type '({ isAdded, errorMessage }: PropsWithChildren<StatusMessageProps>) => Element | undefined' is not assignable to type 'FunctionComponent<StatusMessageProps>'.  Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.    Type 'undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
I am using the same method on different pages but the error is only here

Edit:

I am using this component like this:

 const [isAdded, setIsAdded] = useState(false);{isSubmitted && StatusMessage(isAdded, errorMessage)}

it gives me an error on isAdded that

Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)

react native upload image with axios

$
0
0

I have this datacame from react-native-image-picker

data: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Qtan" => 90kbfileName: "77677.jpg"fileSize: 67542height: 600isVertical: trueoriginalRotation: 0path: "/storage/emulated/0/Download/77677.jpg"type: "image/jpeg"uri: "content://media/external/images/media/18584"width: 399__proto__: Object

and am try to set this data in object type #FromData to upload #img

var binaryDataInBase64 = new FormData();        binaryDataInBase64.append('file', {            // data: response.data,            uri: 'file://'+ response.uri,            name: 'MMM.jpg',            type: response.type        })        console.log('=======================>', binaryDataInBase64)        axios.post('https://danskeclouddemo.com/api/file',            { file: binaryDataInBase64 },            { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data'  } }        ).then(res => {            console.log(res)        }).catch(error => {            console.log(error)        })

and this is BackEnd Postman Working good Postman collection

//======================//======================Edit

Some people talk about the problem from react native version after 0.61.5in this link issues

imports/exports using the ~ sign

$
0
0

I have a components folder where I am defining components like this:

export const ResultAlert: FunctionComponent<ResultAlertProps> = ({  severity,  text,}) => {  const classes = useStyles();  return (<Alert className={classes.alert} severity={severity}>      {''}      {text}</Alert>  );};

In my components folder, I have made an index.tsx file that says:

export * from './alerts/ResultAlert';

Now, I need a way to make imports work like this:

import {ResultAlert} from '~/components';

Currently, this gives me an error that

Cannot find module '~/components' or its corresponding type declarations.

I have seen this work in the past but I am not sure how. What am I missing out? Do I need to setup any framework else for this?

React navigation 5 error Binding element 'navigation' implicitly has an 'any' type.ts

$
0
0

I am new to react-native. I am trying to implement navigation using react-navigation 5. I have two screens Home and profile. These both components have received a navigation prop but typescript is giving me follwoing error

Binding element 'navigation' implicitly has an 'any' type.ts(7031)

How to get rid of this error.

Thank you in advance

NOTE - I am using typescript

App.tsx

import 'react-native-gesture-handler';import { NavigationContainer } from '@react-navigation/native';import { createStackNavigator } from '@react-navigation/stack';const Stack = createStackNavigator();import Home from './screens/home'const App  = () => {  const ProfileScreen = ({}) => {    return <Text>This is Jane's profile</Text>;  };  return (<NavigationContainer><Stack.Navigator><Stack.Screen          name="Home"          component={Home}        /><Stack.Screen name="Profile" component={ProfileScreen} /></Stack.Navigator></NavigationContainer>  );};

Home.tsx

import React from 'react';import { Button } from 'react-native';const Home = ({navigation}) =>{ // error  return (<Button    title="Go to Jane's profile"    onPress={() =>      navigation.navigate('Profile', { name: 'Jane' })    }  />  )}export default Home;
Viewing all 6215 articles
Browse latest View live


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