'React Navigation V5 custom header + Typescript Error: custom property 'rightButtons' does not exist on type 'object' (router.params)
I create custom header:
const header = ({ navigation, route, options, back }: NativeStackHeaderProps): React.ReactNode => {
const buttons: HeaderRightButtons = route.params?.rightButtons || []
return (...)
}
Typescript shows error:
property 'rightButtons' does not exist on type 'object'
In this property Array of "buttons":
type HeaderRightButtons = Array<{ icon: any, action: () => void }>
I try to make extended type:
export type NativeStackHeaderPropsCustomRight =
(NativeStackHeaderProps & {
route: RouteProp<{params?: { rightButtons: HeaderRightButtons }}, 'params'>
}) | NativeStackHeaderProps
But it doesn't solve problem.
Property "rightButtons" does not exist in the "object | (object & Readonly<{ rightButtons: HeaderRightButtons; }>)" type. The "rightButtons" property does not exist in the "object" type.
Without | NativeStackHeaderProps
shows error in screen declaration:
<Stack.Screen ... options={{
header: headerMain,
title: strings.titleEpochs
}} />
Type "({ navigation, route, options, back }: NativeStackHeaderPropsCustomRight) => React.ReactNode" cannot be assigned for type "(props: NativeStackHeaderProps)
How to write correct type?
Or is there a more correct way to pass an object through properties to a custom header?
Solution 1:[1]
I encountered the same error and I resolved in this way:
first of all, be sure you created the NativeStackNavigator specifying your route object
type RouteParamList = {
myScreenName: {
rightButtons: Array<{ icon: any, action: () => void }>
}
}
const Stack = createNativeStackNavigator<RouteParamList>();
then, declare your screen passing function to options
property:
<Stack.Screen
name="myScreenName"
component={MyScreenComponent}
options={({ route }) => ({
header: (props) => <HeaderMain {...props} rightButtons={route.params.rightButtons} />,
})}
/>
So, in your HeaderMain component:
type NativeStackHeaderPropsCustomRight = NativeStackHeaderProps & {
rightButtons: Array<{ icon: any, action: () => void }>
};
const HeaderMain = ({ navigation, route, options, back }: NativeStackHeaderPropsCustomRight) : React.ReactNode => {
// your component here
const buttons: Array<{ icon: any, action: () => void }> = route.params?.rightButtons || []
return (...)
}
export {HeaderMain}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | DharmanBot |