I have created some tabs using react-navigation v2 in react native app. I have created componentDidMount function in which willFocus is called. First time app runs and my desired tab is selected first time, willFocus is not executing. But when I go to different tab and comes back to that tab now willFocus executes. What is the reason willFocus not executes first time and works fine on second time?
Desired tab componentDidMount function
componentDidMount(){
const {navigation} = this.props;
navigation.addListener ('willFocus', async () =>{
console.log("willFocus runs"
});
}
Tab navigator is nested with other navigators but i am only showing the tab navigator below
TabNav: createBottomTabNavigator(
{
TAB1: Screen1,
TAB2: Screen2,
TAB3: Screen3,
TAB4: Screen4,
TAB5: Screen5,
// Map: MapScreen
},
{
initialRouteName: 'Bar',
transitionConfig: NavigationConfig,
navigationOptions: ({navigation})=>({
tabBarIcon: ({focused, tintColor})=>{
const { routeName } = navigation.state;
let iconName, iconSize;
switch(routeName) {
case "TAB1":
iconName = `icon1`;
break;
case "TAB2":
iconName = `icon2`;
break;
case "TAB3":
iconName = `icon3`;
break;
case "TAB4":
iconName = `icon4`;
break;
case "TAB5":
iconName = `icon5`;
break;
default:
break;
}
return <Icon name={iconName} color={tintColor} type="FontAwesome" />;
},
}),
tabBarOptions: {
activeTintColor: 'black',
inactiveTintColor: 'grey',
activeBackgroundColor: '#abaf9b',
labelStyle: {
fontSize: 12,
},
// style for tabbar
style: {
backgroundColor: '#ffffff',
height: 60,
justifyContent: 'space-around',
alignContent: 'center',
alignItems: 'center',
},
// style for tab
tabStyle: {
paddingTop: 7,
paddingBottom: 7
}
},
}
),
I had also this issue and it was reported as a bug fo react-navigation. Check this issue for details.
I have two suggestions to solve the issue.
PS:Check your function again and make sure that calling the function two times doesnt cause any side problems
componentDidMount(){
console.log("willFocus runs") // calling it here to make sure it is logged at initial start
const {navigation} = this.props;
navigation.addListener ('willFocus', async () =>{
console.log("willFocus runs") // calling it here to make sure it is logged at every time screen is focused after initial start
});
}
i was having this issue because i had lazy: true in my tab navigators which was causing this issue. i removed it and now it is working on the first click as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With