Home > OS >  Navigation inside class component not working
Navigation inside class component not working

Time:06-07

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;

CodePudding user response:

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;

CodePudding user response:

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

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