Utilizing useRoute in React Native with TypeScript from @react-navigation/native: A Comprehensive Guide

I need help accessing my incident object from route.params in TypeScript.

Below is the function I use to navigate to my Detail page and pass the incident object:

const navigateToDetail = (incident: IncidentProps): void => {
    navigation.navigate('Detail', { incident });
  };

Here is a snippet of code from my Detail page where I try to retrieve this object from route.params:

type IncidentRouteParams = {
  incident: IncidentProps;
}

const Detail: React.FC = () => {
  const navigation = useNavigation();
  const route = useRoute();

  const incident = route.params.incident;

I believe I need to somehow specify the IncidentRouteParams type when using const route = useRoute()

Thank you for your assistance!

Displayed below is the image showing the error message:

EDIT:

I managed to resolve it by doing the following, although I am unsure if it's the correct approach:

  const route = useRoute<RouteProp<Record<string, IncidentRouteParams>, string>>();

  const incident = route.params.incident;

Answer №1

I just completed this task yesterday!

In summary: To begin, you must create a type that includes each screen name and the parameters it will receive:

type ParamList = {
  Detail: {
    incident: IncidentProps;
  };
};

Next, utilize this parameter and screen name in RouteProp:

const route = useRoute<RouteProp<ParamList, 'Detail'>>();

For more detailed information on these concepts, refer to the documentation here https://reactnavigation.org/docs/typescript

Answer №2

If you want to streamline the process, you can create a specific type based on the ParamList that suits your needs. Simply import this type into your component and pass the RouteName as a parameter.

import { RouteProp } from '@react-navigation/native';

export type StackParamList = {
  Home: undefined;
  Profile: { section: 'about' | 'contact' };
};

export type RouteProps<RouteName extends keyof StackParamList> = RouteProp<
  StackParamList,
  RouteName
>;

Example of how to use:

export const ProfileSection = () => {    
    const route = useRoute<RouteProps<'Profile'>>();
    return <Text>{route.params.section}</Text>
}

Answer №3

This seems unnecessarily complex. There is a simpler way to initialize initialParams in TypeScript.

Here's how you can set it up:

type RouteParamList = {
  Home: { someProp: string; anotherProp: number;};
  Details: React.FC;
  Profile: {isLoggedIn: boolean;};
  Settings: React.FC;
};

const Routes = createNavigator<RouteParamList>();

Then when you want to use it, do the following:

const HomeRoute = (): React.ReactElement => {
  return (<Navigator id="Home" element={
    <Routes.Screen name="Home" component={MainView} initialParams={{ someProp: 'example', anotherProp: 42 }}
      options={{
        title: 'Homepage',
      }}/>
  }/>);
};

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

What is the best way to determine if a child component's property has changed within a method?

The child component is app-google-maps-panel and has 2 properties in the parent component: <div class="col-6"> <app-google-maps-panel [longitude]="longitude" [latitude]="latitude"></app-google-maps-panel> & ...

What is the best way to initiate multiple processes in Node.js and ensure they finish before proceeding?

When working with Node.js and TypeScript, my goal is to initiate multiple processes using the spawn function. Afterwards, I aim to ensure all of these processes are completed before proceeding to execute any additional commands. ...

Unable to execute OAuth2 with Okta using angular-oauth2-oidc framework

Looking to create an authentication module for an Angular application using Okta as the identity provider and implementing the angular-oauth2-oidc flow. Following a guide here: . However, encountering errors when running the web app. How can I troubleshoot ...

having difficulty sending a post request with Angular

Submitting form data via HTTP post will look like this: saveDataFile(mutlidata,id,value): Observable<Response> { var _url = 'http://xxxx.xxx.xxx'; var saveDataURL = _url + '/' + id; var _this = this; ...

Using Cypress.Promise in a Cypress command causes type conflicts

When using Cypress 8.x.x, the following Cypress command works fine: declare global { namespace Cypress { interface Chainable<Subject> { login(): Chainable<Token>; } } } Cypress.Commands.add('login', () => { ret ...

Having difficulty with node or ts-node/register integrating es2020 (flatMap function not recognized)

For some reason, I am encountering an issue with using flatMap in my node or ts-node environment. It was working perfectly fine before but now I keep getting this error message 'TypeError: [x].flatMap is not a function'. I have made sure that x i ...

Leveraging the injectable service within the end callback function alongside interactJS

When using interactJS with Angular to enable drag and drop functionality for elements with the 'draggable' class, everything was working smoothly until I encountered an issue with using the injected service of the component in the callback functi ...

Guide to integrating a component within another component

Due to the size of this application, I am unable to utilize app.module. Unfortunately, the component I need to implement does not contain a module file. I have attempted to import it and utilize @NgModule, but it has not been successful. An error occur ...

Angular 2 is experiencing difficulty in loading the image

I tried following the steps outlined in this documentation to display an image for my checkbox, but it doesn't seem to be showing up on the user interface. I have read that using an image is necessary for creating a checkbox, so I'm confused as t ...

Create a placeholder for an item without the need for a specific function

Here is my current setup: sandbox.stub(rp, 'get').resolves(successResponse) This method provides a custom response when this line of code is executed: return await rp.get(url, options) However, I'm interested in achieving something like ...

TypeScript excels in typechecking when using two individual assignments, but may encounter issues when attempting typechecking with tuple

I am quite puzzled by a discovery I made and I am seeking to understand why TypeScript is displaying this behavior and what the underlying reason may be. Here is the code snippet: class A { constructor(public name : String, public x = 0, public y = 0) ...

Is there a way to access a specific argument in yargs using typescript?

The idea behind using yargs is quite appealing. const argv = yargs.options({ env: { alias: 'e', choices: ['dev', 'prod'] as const, demandOption: true, description: 'app environment&apos ...

Having trouble rendering a Twitter timeline on an Angular 7 project

I am attempting to embed a Twitter timeline in an Angular page by following the instructions outlined at . However, I am encountering an issue where only the button renders and not the actual timeline itself. The code in my index.html file is as follows: ...

Ensure that the versions of react, react-dom, and react-native are compatible in a single package.json file

I am attempting to create a project that combines both react-native and react. To achieve this, I require a package.json configuration. Below is my current package.json setup: { "name": "reactNativeWeb", "version": "0.0.1", "private": true, "scrip ...

What are the best ways to format text conditionally depending on a form's status?

Is there a way to change the text color in an HTML form to be red when the form is invalid and green when it is valid using Angular 8? (HTML) <p class="status"> Form Status: {{ Form.status }} </p> (TS) Form = this.fb.group({ ...

SolidJS does not support reactivity for arrays of objects

I've been scratching my head trying to figure out why this code isn't working as expected. I'm simply updating an object and expecting it to be refreshed in the DOM, but for some reason, that's not happening. The console log confirms th ...

Utilizing shared state in React components through props

Currently, I am utilizing a shared global state in the following manner: interface DashboardProps extends React.Props<Dashboard> { globalState? : GlobalState } export class Dashboard extends React.Component<DashboardProps, any>{ } Withi ...

Using TypeScript to deserialize JSON into a Discriminated Union

Consider the following Typescript code snippet: class Excel { Password: string; Sheet: number; } class Csv { Separator: string; Encoding: string; } type FileType = Excel | Csv let input = '{"Separator": ",", "Encoding": "UTF-8"}&ap ...

Setting up Jest for an Angular projectorCustom

Setting up Jest for Angular seems straightforward according to different online guides. It involves the following steps: ng new jest-test cd jest-test npm i -D jest jest-preset-angular Make changes to package.json: "test": "jest", [...] "jest": { "p ...

How to Add a Rule to an Existing Application Load Balancer Listener using AWS CDK

When I inherited a project, I discovered an application load balancer with a HTTPS Listener that was set up before I began using CDK. This listener currently has 13 rules in place that route requests based on hostname to different fargate instances, with ...