user19287659
user19287659

Reputation:

Navigation inside class component not working

While using class component I cannot use navigation its telling invalid hooks . How can I use navigation inside class component?

this is what i am trying to acheive , navigation option inside class component. actually i a m newbie .Can anyone help me?

import React, { Component } from 'react';

import { Text ,View ,TouchableOpacity } from 'react-native';

import { useNavigation } from '@react-navigation/native';



class Mpin extends Component {

    const navigation= useNavigation();

  render() {

    return (

      <Text>....</Text>

      <TouchableOpacity onPress={()=>navigation.navigate('LoginPage')}>

          <Text>SetMPIN</Text>

      </TouchableOpacity>

    );

  }

}



export default Mpin;

Upvotes: 5

Views: 12763

Answers (3)

Omar Hosny
Omar Hosny

Reputation: 1

you can use vanilla js in those cases, the following code helps you redirect or navigate to other paths:

window.locate.replace('/pathname')

if you want to use Navigate or useNavigate you will have to convert to function component and not a class component

Upvotes: -1

Bala Vigness
Bala Vigness

Reputation: 457

Actually I can understand what you are trying to say. I came through this same kind of mistakes when I first started.

Use the below functional component inside of your class component like shown . By doing so you can access navigation inside class component.

import React, { Component } from 'react';

import { Text ,View ,TouchableOpacity } from 'react-native';

import { useNavigation } from '@react-navigation/native';

function ForgotMpin() {
  const navigation = useNavigation();
  return (
    <View>
      <TouchableOpacity
        style={...}
        onPress={() => navigation.navigate("ForgotPin")}
      >
        <Text>... </Text>
      </TouchableOpacity>
    </View>
  );
}

class Mpin extends Component {


  render() {

    return (

      <Text>....</Text>


          
          <ForgotMpin screenName="forgotMpin" />


    );

  }

}



export default Mpin;

Upvotes: 0

Ravi
Ravi

Reputation: 35589

You cannot use hooks inside class component. Inside class component you can directly access navigation object from props.

this.props.navigation.navigate('LoginPage')

Upvotes: 8

Related Questions