Often when using react navigation tab navigation, there’s a need to call a method on the screen when the screen is focused or a tab on the tab bar is pressed, be it for screen refresh or any action we need.
Lets build the two:
- Call a screen function when the screen is focused
- Call a screen function when the navigation tab is pressed
Finally, we will have both events (as in the “Search” screen) called on focus and on tab bar press. Focus is called when the screen is visible (by swipe or the initial press on the tab) and the tab bar press is called on each tap after the screen is focused.
This guide assumes you already use
react-navigation@3.The usage is similar for
Call a screen function when the screen is focused
This is supported by react navigation out of the box. Add a listener that will call our function (called
onScreenFocus in the gist below) every time the screen is focused.
Call a screen function when the navigation tab is pressed
First, when registering the screens with
createMaterialTopTabNavigation, we will use the
defaultNavigationOptions to check if the screen has our custom function (
tapOnTabNavigator) registered — we want to call it on tab press.
In the gist below,
getScreenRegisteredFunctions loops through our navigation state until the top navigation screen is found. When found, we check if
tapOnTabNavigator is registered on the screen and call it.
Next, in our Screen Component, we want to add
tapOnTabNavigator as a navigation param so react navigation can call it inside
tabBarOnPress in the code above.
Thank you for reading. On our app, Binge tapping on the navigation button needs a scroll to top and screen refresh, this is the approach we use and works good.
On an unrelated note, are your Macbook Pro animations lagging? You should try switching to the dedicated (more powerful) graphic card when on power — automate it with this app https://gum.co/mac-auto-gpu