Amit Dwivedi
Amit Dwivedi

Reputation: 19

In react-native how to get select tab value or index

In react-native how to get select tab value or index. I am rendering API data in a tab. In our tab multiple dates are coming.

I want to save selected tab value like which date is selected.

Can someone help?

 <Tabs renderTabBar={() => <ScrollableTab />} style={styles.Card_background_Margin} initialPage={0}
                      onChangeTab={(Tab, index) => this.tabChanged(Tab, index)}>


                      {  this.state.dateList.map((lists) => {
                        return(
                      <Tab heading= {lists.items} style={styles.Tab_background}>
                        <ScheduleDays navigation={this.props.navigation} />
                      </Tab>

                      )
                  })
                }

                </Tabs>

And here I am calling that function but in an alert, it's coming [object][object], and for the index, it's coming undefined. If I am selecting any other tab then this function is working.

tabChanged(Tab, index){
  alert(Tab);
}

Upvotes: 0

Views: 3986

Answers (2)

Amit Dwivedi
Amit Dwivedi

Reputation: 19

I have fixed this issue...

initialPage you have to define in constructor like this:

constructor(props) {
        super(props);
           this.state = {
          pageNumber: 1
    }

After that call you method here, you will get selected heading value in alert for me it's working fine.

tabChanged(ref){
   alert(ref);
   }

<Tabs
   renderTabBar={() => <ScrollableTab />} style={styles.Card_background_Margin}
   initialPage={this.state.pageNumber}
   onChangeTab={({ ref }) => this.tabChanged(ref.props.heading)}
>
   {
      this.state.dateList.map((lists) => {
         return(
            <Tab heading= {lists.items}  style={styles.Tab_background}>
               <ScheduleDays navigation={this.props.navigation} />
            </Tab>
         )
      }) 
   }  
</Tabs>

Upvotes: 1

Daniel Grathwol
Daniel Grathwol

Reputation: 1

I had the same issue, because index gives back an object. But the object consist of the three properties (i, ref, from) so with i.i you can get the index of the tab. So in your example

tabChanged(Tab, index){ alert(Tab.i); }

should work.

Upvotes: 0

Related Questions