I am using a class component and I want to navigate from here to another screen. But it says navigate is undefined. I look up to the docs and I realised I need to use userNavigationThis. but i don't how to actually use it. Someone helps please
export default class ReduxScreen extends Component {
render() {
return (
<View>
<Button block style={{ marginHorizontal: 30, marginTop: 50 }} onPress={() => {
//I want to add the useNavigation here
}}>
<Text style={{ color: '#FFF' }}>Start</Text>
</Button>
</View>
)
}}
useNavigation is a hook and hooks can only be used inside a functional component like this.
const navigation = useNavigation()
But as you are using the class component so you can navigate like this.
this.props.navigation.navigate('YouScreen', {paramsIfAny})
But you have to make sure that navigation prop is available in your class component by putting console.log if it's available then the above line will work if not then you have to follow this.
Note: navigation prop is always available in the parent route(Route which is used to navigate some screen)
https://reactnavigation.org/docs/navigating-without-navigation-prop
Another solution is you can pass navigation prop from your functional component to a class component like this.
export default function RootFunction (){
const navigation = useNavigation() // extract navigation prop here
return <ReduxScreen navigation={navigation} /> //pass to your component.
}
class ReduxScreen extends Component {
render () {
return (
<View>
<Button block style={{ marginHorizontal: 30, marginTop: 50}}
onPress={() => {
this.props.navigation.navigate('YourScreen')
// now prop will be available here
}}>
<Text style={{ color: '#FFF' }}>Start</Text>
</Button>
</View>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With