I have a back button that takes the user a screen back, but when there are no screens left to go back, I want it to do something else so this is my code:
<Button onPress={()=>{
if(CanGoBack){ // imaginary 'CanGoBack' variable
this.props.navigation.goBack()
}else{
this.doSomething()
}
}}/>
how can I achieve this?
React-Navigation v3
There is a function in
this.props.navigation
calleddangerouslyGetParent
.It states the following in the documentation:
So we can using the following to get the index of the route
So we could use this in the
onPress
of yourButton
in the following way to check if we are back at the start of the route.Update for React-Navigation v5
From the documentation, we can see that
dangerouslyGetParent
still exists.So it could be possible to use the above method for v3 in v5.
canGoBack() in v5
There is also an undocumented api called
canGoBack()
. This can be accessed from the navigation props in the following way:This property returns a boolean value if you are able to go back in the stack. Meaning we can update the code that we did for
v3
in the following way.However, as this is an undocumented api it is liable to change so it could be risky relying on it.
On React navigation 5, there is a
canGoBack()
function which is super helpful in this case.There is a
canGoBack()
event. I am using React Navigation 5. Though I can't find it in the documentations. to check doconsole.log(this.props.navigation)
.