cetinDev
cetinDev

Reputation: 319

React-Navigation this.props.navigation.navigate undefined is not an object

I am using react-navigation but my codes return ; this undefined is not an object (evaluating '_this2.props.navigation.navigate)

how can i fix this error?

myCodes;

    import React, { Component } from 'react';
    import Login from './components/LoginScreen/LoginScreen';
    import AddNewUser from './components/AddNewUserScreen/AddNewUserScreen';
    import { createStackNavigator } from 'react-navigation';

    class App extends Component{
        render(){
            return(
                <Login />
            );
        }


    }

    const RootStack = ({ createStackNavigator }) => (
        {
          Login: Login,
          AddNew: AddNewUser,
        });

    export default App;

LoginScreen.js

 <TouchableOpacity style={styles.ButtonContainer} onPress={()=> this.props.navigation.navigate('AddNew')}>
<Text style={styles.buttonText} >GİRİŞ</Text>
</TouchableOpacity>  

Upvotes: 2

Views: 371

Answers (1)

Ali SabziNezhad
Ali SabziNezhad

Reputation: 3118

You should start your app by calling RootStack like this:

class App extends Component{
    render(){
        return(
            <RootStack />
        );
    }
}

also you can set initialRout in stack like this:

const RootStack = createStackNavigator({
      Login: Login,
      AddNew: AddNewUser,
}, { initialRouteName: 'Login'} )

Now, as you define, your app will start with login page and it has this.props.navigation by itself so you can use this.props.navigation.navigate('AddNew') without error. But if you need to use navigation from a component, you have to send this.props.navigation from parent to component like this:

<YourComponent navigation={this.props.navigation}/>

Then you can use navigation in YourComponent component. I hope this can help you

Upvotes: 4

Related Questions