React navigation — call screen method on tab bar press

Dejan Blazeski
2 min readFeb 7, 2019

--

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 react-navigation@2.

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.

Register screen focus listener, onScreenFocus() called when the screen is focused initially

Call a screen function when the navigation tab is pressed

First, when registering the screens with createMaterialTopTabNavigation, we will use the tabBarOnPress in 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.

Call tabOnTabNavigator function when the screen is focused and the tab bar is pressed

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.

tapOnTabNavigator will be called when the screen is focused and our tab is pressed

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

--

--

Dejan Blazeski

Founder binge.app. Curious dev. Laravel / Angular / VueJs / React Native / Docker. Love stand up shows.