I'm a beginner in react-native. How can I use the useNavigation hook in a React Class Component?
2 Answers
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} />;
}
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
Kate Sinclair
How to navigate from the Class Component without passing
navigation as a prop?Isaac
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 useNavigationSkyNT
Right, so what would you use as an equivalent?