Khalil Khalaf
Khalil Khalaf

Reputation: 9407

How to navigate from parent navigator to a screen in child navigator?

Let's say I have this navigators structure

const Child = StackNavigator({
    Foo: { screen: FooScreen },
    Bar: { screen: BarScreen }
});

const Parent = StackNavigator({
    Main: { screen: Child },
    Baz: { screen: BazScreen }
});

export default Parent;

How can I access a screen in Child, from a screen in Parent?

I would like for instance, to navigate from Baz to Bar.

Following react-community/react-navigation, it states:

If the screen is a navigator. See Actions Doc for a full list of supported actions.

But heyy link is dead !

So How to Fix a 404 Not Found Error does not sound right, so How can I access a screen in Child, from a screen in Parent?

Upvotes: 2

Views: 2894

Answers (4)

The default behavior of React Navigation v5.x is

Navigation actions are handled by current navigator and bubble up if couldn't be handled

However based on their docs,

If you need to dispatch actions to the nested child navigators from a parent, you can use navigation.dispatch

Now from parent navigator (Baz) with access to navigation props

import { CommonActions } from '@react-navigation/native';

// navigation came from parent props
navigation.dispatch(CommonActions.navigate({ name: 'Bar'}));

Here are the links for reference,

Navigation actions are handled by current navigator and bubble up if couldn't be handled

Navigator specific methods are available in the navigators nested inside

Advanced API Reference - Dispatch

Upvotes: 2

iuliu.net
iuliu.net

Reputation: 7145

If you just can't find any solution (as in my case), just do:

In your nested file:

<StackNavigator ref={(x) => (global.childNavigator = x)} />

In your parent:

global.childNavigator.dispatch(
   NavigationActions.navigate({
       routeName: 'Player',
       params: { },
   }),
);

Upvotes: 0

Marcos Ordieres
Marcos Ordieres

Reputation: 41

You can do:

this.props.navigation.navigate(this.props.navigation.state.routes[1].routeName)

The [1] is the position of the tab in the Array or Screens, and the routeName should be Bar.

Upvotes: 1

Khalil Khalaf
Khalil Khalaf

Reputation: 9407

From Baz

this.props.navigation.dispatch(
  NavigationActions.navigate({
    routeName: 'Main',
    action: NavigationActions.navigate({ routeName: 'Bar' }),
  }),
);

Upvotes: 1

Related Questions