Exploring Screen Navigation in React Native using Typescript

Good day,

I am currently working on a react native app project. I am trying to create a simple example to better understand how the navigation works, but I am having trouble replicating the example provided in the documentation.

Below is an image showing the output of my attempted simulation:

Click here for image preview

This is the code snippet that I have experimented with:


import React from 'react';
import { Button, SafeAreaView, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator, NativeStackNavigationProp } from '@react-navigation/native-stack';
import Index from './components/IndexView';

type RootStackParamList = {
  Home: undefined;
  Profile: { name: string };
};

type HomeScreenProps = {
  navigation: NativeStackNavigationProp<RootStackParamList, 'Home'>;
};

const HomeScreen: React.FC<HomeScreenProps> = ({ navigation }) => {
  return (
    <Button
      title="Go to Jane's profile"
      onPress={() => navigation.navigate('Profile', { name: 'Jane' })}
    />
  );
};

type ProfileScreenProps = {
  navigation: NativeStackNavigationProp<RootStackParamList, 'Profile'>;
  route: { params: { name: string } };
};

const ProfileScreen: React.FC<ProfileScreenProps> = ({ route }) => {
  return <Text>This is {route.params.name}'s profile</Text>;
};

const MemoizedProfileScreen = React.memo(ProfileScreen); // Wrap ProfileScreen with React.memo

const Stack = createNativeStackNavigator<RootStackParamList>();

function App(): JSX.Element {
  return (
    <NavigationContainer>
      <SafeAreaView>
        <Stack.Navigator>
          <Stack.Screen
            name="Home"
            component={HomeScreen}
            options={{ title: 'Welcome' }}
          />
          <Stack.Screen
            name="Profile"
            component={MemoizedProfileScreen} // Use MemoizedProfileScreen here
          />
        </Stack.Navigator>
      </SafeAreaView>
    </NavigationContainer>
  );
}

export default App;

Answer №1

This problem was tackled through the following method:

import { useNavigation } from '@react-navigation/core';
const navigation = useNavigation();
onPress={()=>{navigation.navigate('Home')}} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Numerous JavaScript errors are present in the ASP.NET Core Template Pack for Angular 2, causing issues with functionality

After discovering the ASPNETCoreTemplatePack by MadsKristensen, I was excited to use it as a foundation for developing ASP.NET Core applications with Angular 2. However, upon delving into editing, I encountered a whopping 448 errors in the error-list dialo ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

Access information from a different component within the route hierarchy

Suppose you have three components named A, B, and C with the following routing direction: A -> B -> C To retrieve data from the previous component (going from C to get data from B), you can use the following lines of code: In Component C: private ...

When working in React, I often encounter the frustrating TypeError: Cannot read property 'content' of undefined error

Trying to customize a React project, I attempted to add a class to a div using the following code: <div className={styles.content}> In the case of deleting the Data Source, you will lose all configuration sett ...

Converting an array into an object in Angular for query parameters

In my Angular 12 application, I have an array of objects that I need to convert into query parameters in order to route to a generated URL. The desired query parameters should look like this: Brand:ABC:Brand:XYZ:Size:13x18:Size:51x49x85 [{ "values&q ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

Is there a way to define type information for a global variable when utilizing dynamic import within a function?

Here is a simplified version of my server code: server.ts import google from "googleapis"; const androidPublisher = google.androidpublisher("v3"); app.use('something', function(req, res, n){ ... }) ...(only one of the dozens of other meth ...

TS2339 Error: The property 'Default' is not a valid property for type 'string'

Hello, I am a beginner with Angular 2. I have encountered some issues that I need help with: Error Messages: app/components/playing-cables/-update.ts(82,12): error TS2339: Property 'options' does not exist on type 'jQuery'. app/compone ...

I seem to be invisible to the toggle switch

I currently have a toggle button that controls the activation or deactivation of a tooltip within a table. Right now, the tooltip is activated by default when the application starts, but I want to change this so that it is deactivated upon startup and on ...

Tips for sending data in Angular 8's Http GET method within a service class, especially when the backend requires a dictionary format

I am working on a C# backend with an HttpGet method that is expecting a dictionary as request parameters. public async Task<IActionResult> Search([BindRequired, FromQuery] IDictionary<string, object> pairs) Currently, my frontend is built in A ...

Unable to turn off pop-up dialog box and keyboard when tapping outside

I've encountered an issue with the react-native-popup-dialog npm where, when I click outside of the popup, it only closes the popup but the keyboard remains active. To dismiss both the popup and the keyboard at the same time, I need to double tap outs ...

Using JavaScript to create a timer

How should I go about implementing basic timer functionality? Should I use a for loop, or is there another loop that could work better? I want to print the value of x in the function "hello()" after creating a 30-second delay. I'd like it to print so ...

Filtering an array in Angular based on two specific property values

I am facing a challenge with deleting items from an array based on two property values. If we were to compare it to the classic Sql delete command, the equivalent would look something like this: DELETE oImages WHERE idOffertRow = 1 and idProductImage = 2 ...

Retrieve the matching values from a JSON object by filtering it with an array, then create a new JSON object containing only

var structureInfos = [{ name: 'HMDB0006285', identifier: 'Six two eight 5' }, { name: 'HMDB0006288', identifier: 'Six two double eight'}, { name: 'HMDB0006293& ...

Error429 was received from a GET request made to the Imgur API

Encountering a Request failed with status code 429 error from the Imgur API despite using a new Client_ID that hasn't been used before, Here is my Api.ts: const imgurClientId = process.env.NEXT_PUBLIC_Client_ID const BASE = "https://api.imgur. ...

Angular error TS2339: The property 'before' is not found on type 'HTMLElement' / 'HTMLTextAreaElement' / etc

Objective: My goal is to reposition a div (containing a mat-select dropdown) ABOVE a mat-card-title when the user is accessing the site from a mobile device. If the user is not on a mobile device, the div should remain in its original position to the right ...

Angular version 5 consistently replaces the chosen date with the current date

Currently facing an issue with an input field that contains a date. Whenever a date is selected that is not today's date, it always defaults to the current date and gets saved in the backend. I need the selected date to be saved instead. The console l ...

Having trouble activating the Invalidate Cache function in rtk query with tags

Here is a snippet from my Api.js file: export const api = createApi({ reducerPath: 'api', baseQuery: fetchBaseQuery({ prepareHeaders: (headers, { getState }) => { const userInfo=JSON.parse(localStorage.getItem('userInfo' ...

Utilizing PrimeNG's p-dataView feature without repetitive FieldSets

Currently, I am utilizing p-dataView and I'm interested in implementing p-fieldset based on the application type. My goal is to prevent the fieldset from being duplicated when multiple instances occur. The scenario below illustrates one such case; how ...

Adding a badge to a div in Angular 6: What you need to know!

How can I add a badge to a specific div in Angular 6? I have dynamic div elements in my HTML. I want to increase the counter for a specific div only, rather than increasing it for all divs at once. For example, I have five divs with IDs div1, div2, div3, ...