Search code examples
react-nativenavigator

React-Native <Navigator/> : How do I control it from the class that instantiated it


I have a instantiated in my index.ios.js file like this:

render() {
    return(
      <Navigator
        style={styles.navigator}
        renderScene={this.renderScene}
        initialRoute={{
          component: test,
          navigationBar: <NavigationBar title="home" />
        }}/>
    );
}

From this same file I have a function that I would like to be able to trigger an action on the navigator e.g.

resetStack(){
  // navigator.popToTop();
}

How do I achieve this? I thought I had to use something called refs and have tried adding a reference as follows:

render() {
    return(
      <Navigator
        ref="ref1"
        style={styles.navigator}
        renderScene={this.renderScene}
        initialRoute={{
          component: test,
          navigationBar: <NavigationBar title="home" />
        }}/>
    );
}

then calling this with: resetStack(){ // navigator.popToTop(); ref1.popToTop(); }

But this results in an error: Can't find variable ref1

How do I achieve this? How do I trigger methods in child components?


Solution

  • For anyone else with this issue. I was quite close with the above code but neglected to add the this.refs.referenceName to the call, the final code was:

    render() {
        return(
          <Navigator
            ref="ref1"
            style={styles.navigator}
            renderScene={this.renderScene}
            initialRoute={{
              component: test,
              navigationBar: <NavigationBar title="home" />
            }}/>
        );
    }
    

    and call this with:

    resetStack(){
      // navigator.popToTop();
      this.refs.ref1.popToTop();
    }