Search code examples
reactjsnavigatorreact-native

evaluating ( this.props.navigator ) Undefined is not an object


I'm getting this error even though i'm passing in the navigator porp properly.

MySetup is in this way : Main navigator Page -> FirstView (onBtnPress) -> Details

I'm getting the error when i'm calling this.navigator.push in the firstView page.

Main File:

import React, { Component, PropTypes } from 'react';

import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Navigator
} from 'react-native';

class app extends Component{

    constructor(props) {
        super(props); 
    }


   navigatorRenderScene(route, navigator) {
        return <route.component navigator={navigator}/>

  }
     configureScene() {
    return Navigator.SceneConfigs.VerticalDownSwipeJump;
  }


    render() {

      return (
     <Navigator
        style={styles.container}
        initialRoute= {{component: MainMapView}}
        renderScene={this.navigatorRenderScene}/>
      );
    }
}


const styles = StyleSheet.create({
  container: { flex: 1, flexDirection: 'column', padding: 20 }
});

AppRegistry.registerComponent('app', () => app);

First Component:

    <ActionButton buttonColor="rgba(30,144,255,1)" style={styles.fabIcon}
                  onPress={this.fabPress}>
    </ActionButton>


  fabPress() {
  this.props.navigator.push({
      component : DetaislView
    });
  }

The error occurs on fabPress.

Any ideas on what i'm doing wrong?


Solution

  • try this in your FirstComponent.js:

    class FirstComponent extends Component {
    
        constructor(props) {
            super(props); 
            this.fabPress = this.fabPress.bind(this);
        }
    
        // ... rest of the code remains the same
    

    Why we had to do this?

    Back in time when we were using React.createClass (ES5), class methods were automatically bound to the class. But when we started to extend (ES6 classes), we need to bind the methods explicitly to the class env.

    fabPress being passed as an event's callback function, it is executed in another env outside the class; hence the this will be coming from the scope of execution env. But we need this of our class to access this.props.navigator :)