Soujanya Barman Soujanya Barman - 8 days ago 6
React JSX Question

React Native- How can I call a function of a child view from its parent?

I am new on react native and came accross this problem. I have a tab view with 2 tabs in tabview.js file and tab1.js and tab2.js for tab1 and tab2.
So when the page loads the both tabs componentDidMount function calls loadData function which fetches data from web. Now I want to refresh the data when I change tabs. But how can I call the loadData function of tab1.js inside tabview.js?

Here are codes I am using

tabview.js

render() {
return (
<View style={{flex: 1}}>
<Header style={{flex: 1}} />
<ScrollableTabView style={{flex: 10}} onChangeTab={(e)=>{this.checkTabPosition(e)}}>
<Tab1 tabLabel="Tab1" navigator={this.props.navigator}/>
<Tab2 tabLabel="Tab2" navigator={this.props.navigator} />
</ScrollableTabView>
</View>
);
}


tab1.js

render() {
return (
<ScrollView refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
/>
}
>
<View>
<ListView style={styles.listview}
dataSource={this.state.dataSource}
renderRow={(rowData) => <ListItem rowData={rowData} navigator={this.props.navigator} />}
enableEmptySections={true}
/>
</View>
</ScrollView>
);
}

componentDidMount(){
this.fetchData();
}


Same in tab2.js

Answer

You have to add a ref to your Tabs and then use this.refs. Your code will look like this:

checkTabPosition(e){
    // determine which tab to refresh
    var tabToRefresh = ...;

    // refresh tab
    refreshTab(tabToRefresh);
}

refreshTab( tab ){
  this.refs[tab].fetchData();
}

render() {
 return (
    <View style={{flex: 1}}>
       <Header style={{flex: 1}} />
       <ScrollableTabView style={{flex: 10}} onChangeTab={(e)=>    {this.checkTabPosition(e)}}>
          <Tab1 ref="tab1" tabLabel="Tab1" navigator={this.props.navigator}/>
          <Tab2 ref="tab2" tabLabel="Tab2" navigator={this.props.navigator} />
       </ScrollableTabView>
    </View>
 );
}