Cannot read property 'navigate' of Undefined in React Navigation

Viewed 34016

i'm React Native newbie. What i'm trying to do is added react navigation to my login page where user can click a button and navigate to the sign up page but i'm getting an error Cannot read property 'navigate' of Undefined. I've already searched the solution over an internet but no luck. This So does not help me - React Navigation - cannot read property 'navigate' of undefined and same with others .

Here is my code

index.ios.js

import React, { Component } from 'react'; 
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Login from './src/screens/Login';
import Signup from './src/screens/Signup';

export default class tapak extends Component {
  constructor(props) {
    super(props);
    this.buttonPress = this.buttonPress.bind(this);
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={{color: 'blue'}} onPress={this.buttonPress}>sign up</Text>
      </View>
    );
  }

  buttonPress() {
    console.log('called');
    this.props.navigation.navigate('Signup');
  }
}

const Stacks = StackNavigator({
    Login: {
      screen: Login
    },
    Signup:{
      screen: Signup
    }
});
4 Answers

The only answer to this question is to just put const { navigate } = this.props.navigation in your render() function and then you can use it in any component that you need

For Example

render() {
const { navigate } = this.props.navigation;
 return (
  <View>
    <Text>This is the home screen of the app</Text>
    <Button
      onPress={() => navigate('Profile', { name: 'Brent' })}
      title="Go to Brent's profile"
    />
  </View>
);
}

Please read this doc for https://reactnavigation.org/docs/en/navigation-prop.html

Related