How to set navigationOptions on stateless component with Typescript
If the case is that you want the same navigation option for all your components, remember you can set the defaultNavigationOptions
in the createStackNavigator
. Here is the React Navigation API if you need an example.
The key idea is to specify correct type for Example
constant. Probably, react-navigation
already provides that type. But, you can also extend build-in React
interface smth like this:
interface NavStatelessComponent extends React.StatelessComponent {
navigationOptions?: Object
}
const Example: NavStatelessComponent = () => {
return (
<View>
...
</View>
)
}
Example.navigationOptions = {
/*
...
*/
}
Example.propTypes = {
/*
...
*/
}
You can use the following:
import {
NavigationScreenProps,
NavigationScreenComponent
} from 'react-navigation'
interface Props extends NavigationScreenProps {
// ... other props
}
const MyScreen: NavigationScreenComponent<Props> = ({ navigation }) => {
// ... your component
}
MyScreen.navigationOptions = {
// ... your navigation options
}
export default MyScreen
For react-navigation
v4, where you have react-navigation-tabs
and react-navigation-stack
as separate libraries, you need to do something similar to Sat Mandir Khalsa's answer, but you just need to use the correct types from the correct library. For example, if it is a screen from createStackNavigator
, you need to do:
import {
NavigationStackScreenComponent,
NavigationStackScreenProps
} from 'react-navigation-stack'
interface Props extends NavigationStackScreenProps {
// your props...
}
export const HomeScreen: NavigationStackScreenComponent<Props> = ({ navigation }) => {
return (
<View>
<Text>Home</Text>
</View>
)
}
HomeScreen.navigationOptions = {
// your options...
}
Likewise, the react-navigation-tabs
library has types like NavigationBottomTabScreenComponent
and NavigationTabScreenProps
that you can use instead.