2

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;

3 Answers3

7

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

this.props.navigation.navigate('LoginPage')
Ravi
  • 34,851
  • 21
  • 122
  • 183
  • 2
    this should be the accepted answer. you don't need some get around when you can directly access what you need. – omer.ersoy Jun 07 '22 at 06:42
0

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;
Bala Vigness
  • 371
  • 1
  • 3
  • 10
-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