TypeError: navigation.navigate is not a function

4.1k views Asked by At
import React from 'react';
import {Button, View, Text} from 'react-native';

const RegistrationScreen = (navigation: any) => {
  return (
    <View>
      <Text>My Registration Page</Text>
      <Button
        title="Go Back"
        onPress={() => navigation.navigate('HomeScreen')}></Button>
    </View>
  );
};

export default RegistrationScreen;

I am getting the error, when i use .tsx as extenstion of the file. ex: - RegistrationScreen.tsx, and then got the error // TypeError: navigation.navigate is not a function. (In 'navigation.navigate('HomeScreen')', 'navigation.navigate' is undefined) //

2

There are 2 answers

6
Linda Paiste On BEST ANSWER

navigation: any says that the variable navigation can be anything. It can be a number, an object, undefined, etc.

navigation.navigate('HomeScreen')

Then you try to access a property navigate on your variable navigation and furthermore you are assuming that this property is a function which takes a string argument.

Typescript should tell you “hold up, I don’t know that I can do this!”

You should be able to import a type definition for navigation from the react-navigation package. If not, this is sufficient for this particular usage:

interface Navigation {
     navigate(destination: string): void;
}

But what you’re getting looks to be a runtime error because you meant for the arguments of your component to be a props object containing a prop “navigation”, but you’ve written it so that the whole props object is called “navigation”. This is what @realard is talking about in their answer about object destructuring.

In plain JS it would be:

const RegistrationScreen = ({navigation}) =>

But for typescript, we need to declare that the navigation property must by of type Navigation. Which you can do in either of these ways:

Declare the definition for the props object inline

const RegistrationScreen = ({navigation}: {navigation: Navigation}) =>

Declare a type or interface for the props

interface RegistrationProps {
     navigation: Navigation;
}

const RegistrationScreen = ({navigation}: RegistrationProps) =>
2
Arbnor On

You will need Object destructuring for your function RegistrationScreen. You can access navigation from the props with that addition:

const RegistrationScreen = ({navigation: any}) => {}