4

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

2 Answers 2

10

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} />;
}

Sign up to request clarification or add additional context in comments.

2 Comments

The same trick with useNavigate() worked for me, too. Thanks!
I couldn't understand the code snippet. Is the function 'function()' to be invoked in the render() method of the class component in order to get the navigation?
0

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

3 Comments

How to navigate from the Class Component without passing navigation as a prop?
You should not mix them up, when you want to use useNavigation, it is a hooks and you should use it in function based component, if you need navigation in your class based component, dont use useNavigation
Right, so what would you use as an equivalent?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.