Kate Sinclair
Kate Sinclair

Reputation: 493

How to use React Navigation useNavigation Hook in a class component?

I'm a beginner in react-native. How can I use the useNavigation hook in a React Class Component?

Upvotes: 4

Views: 8681

Answers (2)

Isaac
Isaac

Reputation: 12874

useNavigation is a hooks so you should probably use it in a functional component. One simple example is as follow:

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

const SomeButton = () => {
  const navigation = useNavigation();

  return ( 
    <TouchableOpacity onPress={() => navigation.navigate('HomePage')}>
    </TouchableOpacity>
  )
}

Typically you use navigation to navigate to any other screen, but of course it supports whole lot of other advance features too

Upvotes: 0

Amjed Ali
Amjed Ali

Reputation: 420

From Documentation - You can wrap your class component in a function component to use the hook:

class MyBackButton extends React.Component {
  render() {
    // Get it from props
    const { navigation } = this.props;
  }
}

// Wrap and export
export default function(props) {
  const navigation = useNavigation();

  return <MyBackButton {...props} navigation={navigation} />;
}

Upvotes: 10

Related Questions