Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the navigation.navigate inside a createMaterialTopTabNavigator

I started out a bit with react-native, and I'm trying to make a "hello word" app to see how it works. I made a menu with "tab" at the top of my screen

In the app.js I'm adding the createStackNavigator to set my routes App.js

import { ... }
const AppNavigator = createStackNavigator({     
    Main: { screen: Main},
    CScreen: {screen: FormCScreen},
});

type Props = {};
export default class App extends Component<Props> {
render() {
    return (
        <AppNavigator />    
    );
  }
}

This is my main screen, where I set the tabs.

Main.js

imports {AScreen, BScreen} ...
const Tab = createMaterialTopTabNavigator(
{
   A: AScreen,
   B: BScreen,
},
{
  tabBarPosition: 'top',

});

export default class Main extends Component {

render() {
    return (  
      <Tab/>
    );
  }
}

BScreen.js

Now on one of my BScreen tabs, I want to click on a button, where I hope it loads the screen (CScreen)

imports ...
export default class BScreenextends Component{

    render(){
        return(
            <View>
               <TouchableHighlight onPress={() => this.props.navigation.navigate('CScreen')}>
                <Text>Click here to open CScreen</Text>
                   </TouchableHighlight>
            </View>
        );
    }
}

It can render all components correctly, the only problem is that when I click the button to display the CScreen, nothing happens. It is as if loading the Tab I lost the instacia of my navigator.

Main
 Tab 
 A
 B Button (Open CScreen) ~> this is not working

How can I open the screen through a button inside a tab?

[EDIT] Console.log ScreenB

https://imgur.com/a/teAzpn5

like image 532
Emiry Mirella Avatar asked Jun 18 '18 19:06

Emiry Mirella


Video Answer


1 Answers

I think your trying to achieve StacksOverTabs mode of navigation setup,

The mistake you made is Main screen being a normal Component inside which you have rendered the Tab Component i.e createMaterialTopTabNavigator. Hence the Tab Component will not get the correct navigation prop from the StackNavigator

Instead, you have to make Main screen itself a createMaterialTopTabNavigator.

For example,

 const AppNavigator = createStackNavigator({     
     Main: { screen: MainTab}, // MainTab is itself a TabNavigator now
     CScreen: {screen: FormCScreen},
 });

 const MainTab = createMaterialTopTabNavigator(
   {
      A: AScreen,
      B: BScreen,
   },
   {
     tabBarPosition: 'top',

   });
 );

Check out the official examples code in GitHub, inside that navigate to StacksOverTabs

https://github.com/react-navigation/react-navigation/tree/master/examples/NavigationPlayground/js

Thanks.

like image 194
Ravi Raj Avatar answered Sep 28 '22 09:09

Ravi Raj