I am using react-navigation @4.0.5 with react-navigation-stack @1.8.0.
I am setting a header property defaultNavigationOptions present in createStackNavigator method in order to set the default header in multiple screens.
Things work fine I am able to render the header correctly but I can't use hooks like useState in the code of my Header Component.
Below are snippets of how I am using createStackNavigator and createSwitchNavigator respectively.
const ContentStackNavigator = createStackNavigator(
{
Search: SearchScreen,
Result: ResultScreen
},
{
initialRouteName: 'Search',
defaultNavigationOptions: {
header: Header
}
}
)
const SwitchNavigator = createSwitchNavigator({
Init: Screens.Init,
Content: ContentStackNavigator
},
{
initialRouteName: 'Init'
})
My Header is just a plain functional component(take this as a reference).
import React, { useState } from 'react';
import { Text } from 'react-native'
export default (props) => {
const [myState, setMyState] = useState(false);
return (
<View>
<Text>Hello</Text>
</View>
)
}
Below are the logs:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
I know the above error is related to version mismatching and incorrect usage of hooks so I had tested the above things already. All other components seem to be working so I highly suspect this is related to the react-navigation library and its header.
Correct me if I am doing something wrong and what is the way around?
As mentioned by @ashwith in comments, I needed to pass:
Note: Navigation props would not be passed in the Header component directly with this approach so I'd use the following:
I hope this helps someone in the future.