Navigation Lifecycle
Cancelling Navigation
The onBeforeNavigate
event gives you a chance to cancel a navigation. You're passed in details of the State
being navigated to as well as a history
flag that indicates whether the navigation was caused by the browser back button. In our email example, we can add an onBeforeNavigate
listener that prompts the user to confirm they want to leave without sending their email.
import {NavigationContext} from 'navigation-react';
const {stateNavigator} = useContext(NavigationContext);
useEffect(() => {
const beforeNavigate = (state, data, url, history) => (
history || confirm('You\'ve not sent your email. Continue?')
)
stateNavigator.onBeforeNavigate(beforeNavigate);
return () => stateNavigator.offBeforeNavigate(beforeNavigate)
}, [stateNavigator]);
There's also an onNavigate
event that fires after the navigation's happened. We could add an onNavigate
listener that tracks page visits in our email app.