React Navigation V5 typescript error: Trying to add a custom header with a 'rightButtons' property, but encountering an issue with the type 'object' (specifically router parameters) that does not recognize this custom

I am designing a unique header:

const customHeader = ({ navigation, route, options, back }: NativeStackHeaderProps): React.ReactNode => {
    const buttons: HeaderRightButtons = route.params?.rightButtons || []
    return (...)
}

An error is displayed in Typescript:

The property 'rightButtons' does not exist on the type 'object'

This property should contain an Array of "buttons":

type HeaderRightButtons = Array<{ icon: any, action: () => void }>

I attempted to create an extended type:

export type NativeStackHeaderPropsCustomRight =
    (NativeStackHeaderProps & {
        route: RouteProp<{params?: { rightButtons: HeaderRightButtons }}, 'params'>
    }) | NativeStackHeaderProps

However, this did not resolve the issue.

The property "rightButtons" does not exist in the type "object | (object & Readonly<{ rightButtons: HeaderRightButtons; }>)". The "rightButtons" property does not exist in the "object" type.

When excluding | NativeStackHeaderProps, an error appears in the screen declaration:

<Stack.Screen ... options={{
        header: customHeader,
        title: strings.titleEpochs
      }} />

The type "({ navigation, route, options, back }: NativeStackHeaderPropsCustomRight) => React.ReactNode" cannot be assigned to type "(props: NativeStackHeaderProps)

How can I define the correct type?

Is there a more appropriate way to pass an object as properties to a custom header?

Answer №1

I encountered a similar issue and was able to resolve it by following these steps:

Firstly, ensure that you have created the NativeStackNavigator with your specified route object:

type RouteParamList = {
  myScreenName: {
    rightButtons: Array<{ icon: any, action: () => void }>
  }
}
const Stack = createNativeStackNavigator<RouteParamList>();

Next, define your screen and pass the function to the options property:

<Stack.Screen
  name="myScreenName"
  component={MyScreenComponent}
  options={({ route }) => ({
    header: (props) => <HeaderMain {...props} rightButtons={route.params.rightButtons} />,
  })}
/>

In your HeaderMain component:

type NativeStackHeaderPropsCustomRight = NativeStackHeaderProps & {
  rightButtons: Array<{ icon: any, action: () => void }>
};

const HeaderMain = ({ navigation, route, options, back }: NativeStackHeaderPropsCustomRight) : React.ReactNode => {
  // your component logic here

  const buttons: Array<{ icon: any, action: () => void }> = route.params?.rightButtons || []
  return (...)
}

export {HeaderMain}

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 modify the KeyName in an object?

Having difficulty parsing an Object by changing keynames due to the error message "Element implicitly has an 'any' type because expression of type 'keyof SignInStore' can't be used to index type '{}'". interface SignInSto ...

Struggling to make the paste event function in Typescript

Here is a snippet of my Typescript code: const pasteFn = (e: ClipboardEvent) => { const { clipboardData } = e; const text = clipboardData?.getData('text/plain'); console.log(text); }; window.addEventListener('paste', pas ...

Is there a way to initiate validations for inputs within ReactiveForms?

After creating a form using Reactive Forms, I have implemented functionality for users to set a new password. The process involves entering both the old and new passwords, as well as confirming the new password. Throughout development, I considered the fol ...

Redirecting with React Router - Redirecting after Form Submission Leads to Loading HomeRoute

After clicking on the submit button, a method is triggered to retrieve data and redirect to another component for rendering and displaying the data. However, when the component is called, only the basic JSX in the component renders. The menu and table do n ...

Transfer an object to $state.go

I'm having trouble solving this issue. Here's the state I am working with: var myState:ng.ui.IState = <ng.ui.IState> { url: '/new/{order.orderNumber}', controller: 'OrderController', controll ...

The Unusual Behavior of Typescript Partial Interfaces

While reviewing the code in a repository I am currently working on, I stumbled upon something that seemed completely incorrect. Here is a snippet of what caught my attention. interface Car { make: string model: string } type SomeType = Partial<Car& ...

Before proceeding to update in Angular 8, ensure the repository is not dirty. Commit or stash any changes that have been

Encountered an Issue The repository is not clean. Please commit or stash any changes before updating. When upgrading from version 7 to Angular 8, I faced this error. To find out more about the upgrade process, you can visit the Angular Guide for Upgra ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

We were unable to locate a declaration file for the module known as 'firebase-tools'

As I delve into writing my inaugural cloud function for Firebase, I find myself in need of the firebase-tools module. To bring it on board, I updated my dependencies by editing the package.json file and executing the command npm install. Next, I attempted ...

Leveraging ts-loader alongside strip-loader in Webpack

I am currently facing an issue with strip-loader in my Typescript project that is built with Webpack. The ts-loader statement in my project is as follows: { test: /\.ts$/, loader: 'babel-loader?presets[]=es2015!ts-loader' } Everything see ...

Are union types strictly enforced?

Is it expected for this to not work as intended? class Animal { } class Person { } type MyUnion = Number | Person; var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Is this supposed to fail? var x: MyUnion = "jjj"; // Should this actually ...

Retrieve and present JSON information (object, array) using a service provider in Ionic 2 with TypeScript and Angular 2

I am currently delving into Angular 2 and Ionic 2 (not to forget about NodeJS and TypeScript). For testing purposes, I have a list of users available here. Eventually, I will be fetching real user data from an API connected to my database. To handle this ...

Using React JS to Sort an Array Based on a Specific String

Here I am again, this time dealing with reactjs. I have a json object containing two "rows", labeled as Description and ubication. My goal is to filter the array based on the Description field. How can I achieve this? The description is in text format, f ...

What is the best way to update properties in a child component using React hooks?

Looking to update the props using react hooks, I came across a method of passing setState function as props to the child component. MainContainer.tsx const MainContainer: React.FC = () => { const [count, setCount] = useState(0); return <Counter ...

Is there a way to retrieve the chosen value from a select element?

How do I retrieve the chosen value from a select element? In my select.component.ts file: export class PfSelectComponent implements OnInit { constructor() { } ngOnInit() { } @Input() options : Array<Object>; } Contents of select.compon ...

Discovering the 3D coordinates of a point that is perpendicular to the midpoint of a line

(I am working with Javascript/Typescript and Three.js) Given two vectors, let's say {x:1, y:3, z:5} and {x:7, y:8, z:10}, I have a direct straight line connecting them. At the midpoint of this line, envision a disc with a radius of 1 that is perpend ...

When using TypeScript in React Native, the error "TypeError: this.setState is not a function

While working with React Native version 0.39.2 along with the latest TypeScript, I encountered an error when running my componentDidMount() method and trying to setState. The error message indicated that this.setState is not a function. I attempted bindin ...

What are some effective methods for handling data from a backend API within an Angular service?

I'm currently facing challenges in effectively managing and manipulating data retrieved from a backend API within an Angular 2+ service. Take for instance the creation of a cart system. Upon sending an initial get request to fetch the current cart de ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Achieve compliance with the ESLint "no-var-requires" rule by utilizing an import statement for a module that lacks a declaration file

Within my NodeJS/TypeScript project, I am successfully using fluent-ffmpeg. To utilize it, I have to import the path properties from both ffmpeg-installer/ffmpeg and ffprobe-installer/ffprobe. The import for ffmpeg appears as follows: import * as ffmpegIn ...