Thilina Dinith Fonseka
Thilina Dinith Fonseka

Reputation: 644

react-navigation navigate is not a function error. - Class component

I'm using react native class component and I'm using react-navigation to route in the app. the guide is mostly for the functional component and I'm trying to implement it with class components. but when i trying to get it from reactnavigation it always throws me error that navigation is not a function or undefined. Im sorry if this is an already asked question as I'm really new to this react native.

class component

import React from 'react';
import { useNavigation } from '@react-navigation/native';
import { Button, Divider, Layout, TopNavigation ,Card,Text} from '@ui-kitten/components';

class HomeScreen extends React.Component {

     navigateDetails(navigation)  {
         debugger
         navigation('Details');
    };

    constructor(props) {
        super(props);
        console.log(this.props);
        this.state = { hover: false };
    }

    render()  {
        const navigation = this.props;
        return(

            <Button onPress={this.navigateDetails}>OPEN DETAILS</Button>

        );
    }
}

export default function (props) {
    const navigation = useNavigation();
    return <HomeScreen {...props} navigation={navigation} />;
}

Upvotes: 0

Views: 7410

Answers (2)

Waheed Akhtar
Waheed Akhtar

Reputation: 3187

First, you have to make sure navigation prop is exist in your class component (As looking in your code its already exist) and the second thing is this.props.navigation is an object, not a function which holds different function like navigate, push etc so you have to execute these functions, here are some changes I did in your code and I hope this will work for you.

   class HomeScreen extends React.Component { 

    constructor(props) {
        super(props);
        console.log(this.props);
        this.state = { hover: false };
       }
        navigateDetails()  {
         this.props.navigation.navigate('Details');
       };

    render()  {
        const navigation = this.props;
        return(

            <Button onPress={()=>this.navigateDetails()}>OPEN DETAILS</Button>

        );
    }
}

export default function (props) {
    const navigation = useNavigation();
    return <HomeScreen {...props} navigation={navigation} />;
}

Upvotes: 1

Thilina Dinith Fonseka
Thilina Dinith Fonseka

Reputation: 644

Seems I have to pass that navigation to the function as a variable in order to work. so I have changed the function as bellow to pass the navigation to the function and also changed this.navigateDetails(navigation) to ()=>this.navigateDetails(navigation)

also, I destructed the navigation like const {navigation} = this.props;

full code line

 onPress={()=>this.navigateDetails(navigation)} 

Upvotes: 0

Related Questions