frankied003
frankied003

Reputation: 516

How to Navigate from a functional component, from a screen in a tab navigator, where that tab navigator is nested in a parent stack navigator

HomeStackNavigator(stack)
---HomeTabsNavigator(Tab)
   ---FirstTab(stack)
      ---CreatePost(screen)
      ---Posts(Tab)
         ---Following(screen)
         ---Feed(screen) <----- functional component in here, lets call it component1
   ---SecondTab
      ...
---Screen2

I want to be able to navigate from a functional component in the feed screen to screen 2. I've tried looking at the nested navigation docs in react native docs but no luck.

Upvotes: 1

Views: 689

Answers (1)

bas
bas

Reputation: 15462

You can use the RootNavigation approach: https://reactnavigation.org/docs/navigating-without-navigation-prop/

First you create a file at your directory root called RootNavigation.js that looks like this:

import * as React from 'react';

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}

Then you pass the navigationRef as a ref to your NavigationContainer:

import * as RootNavigation from './RootNavigation';
// ...
<NavigationContainer ref={RootNavigation.navigationRef}>
   <HomeStackNavigator />
</NavigationContainer>

This allows you to navigate from anywhere.

Then you can do something like this in your Feed screen:

const Feed = () => {
    // ...
    <Button
      title="Navigate to SecondTab"
      onPress={() => RootNavigation.navigate('SecondTab')}
    />
    // ...
};

Upvotes: 6

Related Questions