1

I have a TabView component that has multiple tabs containing components. These components have entire hierarchies of other components. How could I know from any child component nested arbitrarily deep in one of these hierarchies whether or not it's parent tab is in focus in the TabView?

Preferably, I would want to implement this similar to react-navigation's withNavigationFocus (or an equivalent hook) so that any component can know if it's in tab focus without having to pass props down the chain of components. I'm thinking you could have a TabViewContext that components can register themselves as focus listeners to by doing a useContext. The TabViewContext would be provided by the TabView and the TabView would be responsible for determining what registered listeners are in focus when tabs change. My dilemma is I don't know how the TabView could determine efficiently what nested child components come into focus when the tab changes. Any ideas?

Scooter
  • 1,031
  • 1
  • 14
  • 33

1 Answers1

0

In case the other parent tabs are hidden, you could test for visibility in plain JS, rather than have a much more complex solution... Checkout this answer on how to do this.

So components that care about the visibility of their parent tab could use a ref for their own DOM elements and test whether they're visible or not. You could build this into a simple helper function or a hook

EDIT:

I'd suggest going with something like this:

Each Tab will provide a context with method for any descendant to register a callback that will be called when the Tab is hidden. The TabView can pass a "isVisible" prop to each tab (if it doesn't already), so Tab can know when its display changes.

When a Tab changes from visible to hidden. All registered callbacks will be called.

I would of course write a hook or a helper function to create this TabVisibilty context so each Tab component can use it in a reusable manner.

poeticGeek
  • 1,001
  • 10
  • 14
  • I investigated visibility checking, it doesn't seem to be very easy to do it in react native. I think it could be a great, simple solution but I just don't know how to do it. – Scooter Jul 15 '20 at 02:55
  • sorry. missed the fact that its RN... I'll ask a question then. Why do you need to know from child components whether they are in a visible tab or not – poeticGeek Jul 15 '20 at 06:46
  • Because I have autoplay functionality for a list of videos in a component somewhere in the tab view. When the tab goes out of focus, the autoplay controller needs to know so it can pause the currently playing video (this is necessary because I'm not unmounting components when tabs switch). – Scooter Jul 16 '20 at 00:03
  • @Scooter were you able to solve this? If so, how? I made a discussion post [here](https://github.com/satya164/react-native-tab-view/discussions/1270). – macsj200 Sep 27 '21 at 19:47