Search code examples
react-nativereact-navigationtabnavigator

How can I pass data using Tab Navigation in react-Native? (React Navigation)?


This is my Main.js file which included my "Tab" component

Main.js

    <View>
     </Tab>
    </View>

This is my Tab.js file:

const mainTab = TabNavigator(
{
TabItem1: {
  screen: gameTab,
  navigationOptions: ({ navigation }) => ({
    tabBarLabel: "Tab1",
  })
},

TabItem2: {
  screen: Abc,
  navigationOptions: ({ navigation }) => ({
    tabBarLabel: "Tab2",
  })
},

TabItem3: {
  screen: Abc,
  navigationOptions: ({ navigation }) => ({
    tabBarLabel: "Tab3",
  })
}
},
 {
initialRouteName: "TabItem1",
tabBarComponent: TabBarBottom,
tabBarPosition: "bottom",
animationEnabled: true,
tabBarOptions: Platform.OS === "ios" ? iosTabBarOption : 
androidTabBarOption
 }
);

export default mainTab;

And this is my gameTab:

const gameTab = TabNavigator({
t1: { screen: mainlist, navigationOptions: { title : 'tab1', header:null}},
t2: { screen: Abc,      navigationOptions: { title : 'tab2', header:null}},
t3: { screen: Abc,      navigationOptions: { title : 'tab3', header:null}},
t4: { screen: Abc,      navigationOptions: { title : 'tab4', header:null}},
t5: { screen: Abc,      navigationOptions: { title : 'tab5', header:null}},
},{
tabBarComponent: TabBarTop,
tabBarPosition: 'top',
animationEnabled: true,
swipeEnabled: false,
lazy: false,
tabBarOptions: Platform.OS === 'ios' ? iosGameTabOption : 
androidGameTabOption,
});

export default gameTab;

And finally, this is my mainlist.js:

....

let arr = [[1,2,3], [2,3,4], [3,4,5]];

....

So my question is: I have an array in mainlist.js and I want to pass it back to my Main.js. How can I do that?

I know I can use ScreenProps to send data from Main.js to mainlist.js but I have no idea how to send it back.

Thanks in advance!!!!


Solution

  • Since your data is static or does not vary according to the Tab that opens, all you have to do is export the array from mainlist.js.

    // mainlist.js
    let arr = [[1,2,3], [2,3,4], [3,4,5]];
    
    export default { arr };
    

    And import that array into each of the Tabs that you need it.

    // Abc tabs components. Abc.js
    import { arr } from "./mainlist.js";
    

    And use the data according to your needs. You can also use redux and maintain a global tree with your data.

    If you decide to change Tabs dynamically, you can pass parameters to each screen.

    For more information: https://reactnavigation.org/docs/en/params.html