Turning off BarCodeScanner


#1

We are currently using a BarCodeScanner in an app with a react-navigation tab-navigator.
When navigating away from the component, the camera stays active. What’s the best way to toggle the camera on/off - be it on the actual page or when navigating away?


#2

Hello! The basic idea here is that you should hide the BarCodeScanner when the tab is not focused, and show it when it is focused.

react-navigation has pretty awkward support currently for subscribing for focus and unfocus events. See this long discussion about it for more info.

I had to do this recently and I found the most pleasant way to do it for the tab bar was to fork the built-in tab bar and have it support a onPressTab prop. Next, in the TabNavigator tabBarOptions I emit an event if the selected tab is pressed – this is because I only cared about knowing when the user tapped on the icon for an already selected tab. You could remove the if here. NavigationEvents is just an EventEmitter. Finally, I subscribe to the tab events on my screen where I care about it.

Possibly one of the solutions in the react-navigation issue I linked to would be more straightforward, and ultimately react-navigation needs to include a solution for this into the core itself. I hope this helps, though!


#3

Hi @notbrent - super detailed detailed explanation and code links - that’s a really useful way of dealing with this scenario. In the particular app we are working on now we have now tapped into the Redux Navigation info and are showing/hiding the scanner accordingly. Looks good, and the battery drain should be over :four_leaf_clover: Having now worked more with react-navigation and following the thread above and others, I’d also be looking forward for more in-built support for the focus/unfocus event. Many thanks :smiley:


#4

Hello, i am new to the Expo. when you say hide the BarCodeScanner/Camera, is it to set it’s display property to ‘none’, or totally remove it from render()?

i have the same issue of having a camera within a tab screen. it works well when the tab firstly was rendered, after switching to other tab and switching back to the camera tab, it appeared black screen.

thanks!


#5

this can be addressed by giving a render section without ‘Camera’ tag on the navigation ‘didBlur’ event. and bring it back on the ‘didFocus’ event. works well.

thanks!