miguelacio
miguelacio

Reputation: 150

Cannot read property 'navigate' of undefined - React Native Navigation

I am currently working on a app which works with react native and I tried to make a flow using react-navigation working on this tutorial but I am having trouble at the point of running my project, I've done a lot of research and i just cant get to the solution, first for all I am using react-native-cli: 2.0.1 and react-native: 0.48.3, this is my code:

App.js:

import React, { Component } from 'react';
import { Text, Button, View } from 'react-native';
import {
    StackNavigator,
} from 'react-navigation';

class App extends Component {
    static navigationOptions = {
        title: 'Welcome',
    };

    render() {
        console.log(this.props.navigation);
        const { navigate } = this.props.navigation;
        return (
            <View>
                <Text>Go to maps!</Text>
                <Button
                    onPress={() => navigate('Map')}
                    title="MAP"
                />
            </View>
        );
    }
}

export default App;

my Router.js

import {
    StackNavigator,
  } from 'react-navigation';

  import MapMarker from './MapMarker';
  import App from './App';

  export const UserStack = StackNavigator({
    ScreenMap: 
    {
        screen: MapMarker,
        navigationOptions:
        {
            title: "Map",
            header:null
        },
    },
    ScreenHome: 
    {
        screen: App,
        navigationOptions:
        {
            title: "Home",
            headerLeft:null
        },
    },
});

As you can see this is a pretty basic App which i just cant make work, this is a screenshot of my error on the simulator:

Whoops

I would really really appreciate if you guys could help me with this. Thanks.

Upvotes: 0

Views: 2488

Answers (2)

Md Isfar Uddin
Md Isfar Uddin

Reputation: 732

You should change the code onPress={() => navigate('Map')} to onPress={() => navigate('ScreenMap')} and ScreenHome should be the first screen then ScreenMap as you want to navigate from App to MapMarker. Or you can set initialRouteName: ScreenHome in the stacknavigator.

Upvotes: 2

pwcremin
pwcremin

Reputation: 755

You create your StackNavigator, but where do you use it? You should have something like

import React, { Component } from 'react';
import {
    AppRegistry,
    View
} from 'react-native';

    import {
        StackNavigator,
      } from 'react-navigation';

    export default class MyApp extends Component {
      render() {
        return (
          <View style={{flex:1}}>
            <StackNavigator/>
          </View>
        );
      }
    }

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

Now that your StackNavigator is controlling what is shown, your App component will have navigation in its props. Note, you do not "pass" the navigation prop. This is handled for you.

Upvotes: 0

Related Questions