Definition for the type react-navigation-v6 <Stack.Group>

I'm having trouble figuring out the proper type definition for a Stack group that includes screens (refer to TestStack.Group and the nested TestStack.Screen).

The navigation stack:

const TestStack = createNativeStackNavigator<TestStackParamList>();
function TestNavigator() {
  return (
    <TestStack.Navigator initialRouteName="TestScreen">
      <TestStack.Screen
        name="TestScreen"
        component={TestScreen}
        options={{ headerShown: true, title: "", headerTransparent: true }}
      />
      <TestStack.Group screenOptions={{ presentation: "modal" }}>
        <TestStack.Screen name="TestModal" component={TestModal} options={{ title: "" }} />
      </TestStack.Group>
    </TestStack.Navigator>
  );
}

Part of the root stack is defined as:

export type RootStackParamList = {
  TestStack: NavigatorScreenParams<TestStackParamList> | TestScreenParams;
...
}
export type TestStackParamList = {
  TestScreen: TestScreenParams;
  TestResultScreen: TestScreenParams;
  StaticContentScreen: StaticContentParams;
};
export type TestScreenParams = {
  param1: string;
  param2: string;
};

I've attempted the following (among other variations..)

export type TestStackParamList = {
  TestScreen: TestScreenParams;
  TestResultScreen: TestScreenParams;
  StaticContentScreen: StaticContentParams;
  TestModal: RouteGroupConfig<TestStackGroupParamList, NativeStackNavigationOptions>;
};

export type TestStackGroupParamList = {
  TestModal: { simplified: string; type: ModalType };
};

This linter error is being displayed:

Type '({ children, navigation, route, }: TestModalProps) => ReactNode' is not assignable to type 'ScreenComponentType<TestStackParamList, "TestModal"> | undefined'.

The error message is clear, but I am struggling to find the correct "combination" of navigation types.

Answer №1

When dealing with Screens in Stack Groups, there's no requirement for special typings; they can be treated just like those outside the Stack Group. For example, TestStackParamList could be defined as shown below.

export type TestStackParamList = {
  TestScreen: TestScreenParams;
  TestResultScreen: TestScreenParams;
  StaticContentScreen: StaticContentParams;
  TestModal: { simplified: string; type: ModalType };
};

Below is the complete file with typings (some assumptions were made about missing code in the question). You can also verify that there are no type issues in this code by checking out the CodeSandbox.

import React from "react";
import {
  createNativeStackNavigator,
  NativeStackScreenProps
} from "@react-navigation/native-stack";

/* SECTION: SCREENS */
function TestScreen() {
  // TODO: Return the actual component
  return null;
}

type TestModalProps = NativeStackScreenProps<TestStackParamList, "TestModal">;

function TestModal({ route }: TestModalProps) {
  const { simplified, type } = route.params;
  // TODO: Use the route params and return the actual component
  return null;
}
/* END SECTION: SCREENS */

/* SECTION: NAVIGATION */
// TODO: Replace with actual modal types
type ModalType = "type1" | "type2";

export type TestScreenParams = {
  param1: string;
  param2: string;
};

export type TestModalScreenParams = {
  simplified: string;
  type: ModalType;
};

export type TestStackParamList = {
  TestScreen: TestScreenParams;
  TestResultScreen: TestScreenParams;
  StaticContentScreen: StaticContentParams;
  TestModal: TestModalScreenParams;
};

const TestStack = createNativeStackNavigator<TestStackParamList>();

export function TestNavigator() {
  return (
    <TestStack.Navigator initialRouteName="TestScreen">
      <TestStack.Screen
        name="TestScreen"
        component={TestScreen}
        options={{ headerShown: true, title: "", headerTransparent: true }}
      />
      <TestStack.Group screenOptions={{ presentation: "modal" }}>
        <TestStack.Screen
          name="TestModal"
          component={TestModal}
          options={{ title: "" }}
        />
      </TestStack.Group>
    </TestStack.Navigator>
  );
}

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

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

What is preventing me from adding members to an imported declaration?

Currently, I am attempting to include a constructor in an imported declaration. As per the information provided in the documentation, this should be feasible. (Refer to Chapter Adding using an interface) Below is the code snippet that I have used: import ...

Navigating Angular QueryList through loops

I am currently trying to gather all the images in my component and store them in an array. To achieve this, I am utilizing Angular's @ViewChildren which returns a QueryList of ElementRef: @ViewChildren('img', { read: ElementRef }) images: Q ...

Tips for enhancing the TypeScript definition of Material UI 3 theme by integrating the Material UI pickers theme

Trying to enhance the Material-UI theme with the Typescript typings of Material-UI-Pickers for the latest versions listed here: "@material-ui/core": "^3.9.2", "material-ui-pickers": "^2.2.1", A note on the bottom of the Material UI picker page mentions t ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Guide to adding a loading spinner into your Angular project

I've been attempting to incorporate a spinner into my application, but unfortunately, the spinner isn't showing up. Despite checking the console and terminal for errors, there doesn't seem to be any indication as to why the spinner is not a ...

The error message thrown is: "Unable to assign value to property 'formGroup' as it is not defined

There's a particular component structure as shown below: import { Component, Input } from '@angular/core'; import { WorkingHours } from '../../../../../hours'; import { FormGroup } from '@angular/forms'; @Component({ ...

Using TypeORM to Retrieve Data from Many-to-Many Relationships with Special Attributes

Hey there, I'm diving into the world of TypeORM and could really use some guidance. I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here However, I've run into a few iss ...

What is the best way to update state from a triple-layered object?

I am currently working with a nested object that I need to update using setState. Payloads export interface DentistPayload { croNumber: string; person: PersonPayload; } export interface PersonPayload { fullName: string; birthdate: string; cpfNu ...

Typical approach to receiving a transformed object from an HTTP service

One of the services I provide includes a method with the following implementation: public fetchCrawls(page: number): Observable<ICrawl[]>{ return this._http.get(this._crawlsURL + page) .map((res: Response) => { ...

What is the best way to retrieve the `any` type when utilizing the `keyof` keyword?

I am struggling to articulate this question properly, so please refer to the code below interface TestParams<T> { order?: keyof T attr1?: number attr2?: string } async function Test<T = any>(_obj: TestParams<T>): Promise<T> { ...

"Creating a Typescript array by extracting items from a different const array (as seen in the official beginner tutorial

Currently, I am working through the Angular tutorial that can be found at https://angular.io/start. After successfully completing the tutorial, I decided to practice building for production locally. However, when attempting to build, I encountered this err ...

Issue with Async Pipe when connected to a recently generated observable is causing failures

Encountering an error when trying to use the Async Pipe with a newly created Observable? "Cannot read property 'subscribe' of undefined" Check out this Plunkr for a demonstration: https://plnkr.co/edit/vljXImCYoNubjyxOaWo3?p=preview If you com ...

Angular 6 - Build a dynamic single page housing various applications within

I am faced with the task of developing multiple applications using Angular 6. Each application will have its own set of components, services, and more. However, there is also a need for shared services, components, directives, and other elements that will ...

Angular keeps FormArray elements' validity up-to-date as new elements are added to the array

I am facing an issue where I do not want the validators to run unnecessarily. Every element of FormArray is being validated asynchronously, so I prefer the validators to be triggered only when the control's value actually changes. It seems odd that va ...

Is there a way to ensure that only individual objects are selected in FabricJS on the Canvas, rather than a group of objects?

One issue I am facing is with my method for selecting objects on the canvas by clicking a button. How do I ensure that it skips selecting groups and only selects individual objects? Generating a group of shapes here: const group = new fabric.Group([ ...

Having trouble making API calls from the NextJS endpoint

While attempting to access an external API endpoint in NextJS, I encountered the following error message: {"level":50, Wed Jan 24 2024,"pid":4488,"hostname":"DESKTOP-S75IFN7","msg":"AxiosError: Request ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

Implementing an interface with a variable key and defining the key simultaneously

I am trying to design an interface with a fixed key, as well as a variable key, like this : interface Data { api?: { isReady: boolean; }; [key: string]: string; } This setup gives me the following error message : Property 'api' of typ ...

Is there a way to signal an error within an Observable function that can handle multiple scenarios depending on the specific page being viewed in an Angular application?

Currently, I have a function called getElementList() which returns Observable<Element[]>. The goal is to handle different scenarios based on the user's current page - two cases for two specific pages and one error case. However, I am struggling ...