Callbacks
There are a few navigation callbacks to manage the lifecycle of a navigation:
- onNavigate
- onCancel
- onNavigateStart
- onError
- onAbort
- onNavigateEnd
These callbacks can be used as properties to Link and Form elements to be invoked with navigations from these components.
function Route() {
let [Link, busy, loading, navigations] = useLink()
function onNavigate(event) { ... }
function onCancel(event) { ... }
...
return <Link href="/" onNavigate={onNavigate} onCancel={onCancel}>Navigate</Link>
}
function Route() {
let [Form, busy, loading, navigations] = useForm()
function onNavigate(event) { ... }
function onCancel(event) { ... }
...
return <Form action="/" onNavigate={onNavigate} onCancel={onCancel}>
...
</Form>
}
Or use them as an option to the navigate function when navigating programmatically.
function Route() {
let [navigate, busy, loading, navigations] = useNavigate()
useEffect(() => {
function onNavigate() { ... }
function onCancel() { ... }
setTimeout(() => {
navigate("/", { onNavigate, onCancel })
}, 5000)
}, [])
...
}
These callbacks can also be added as properties to the Router element to be called for all navigations of that router.
let Router = Routes(
<App>
<Todos path="todos" />
...
</App>
)
function Application() {
function onNavigate(event) { ... }
function onCancel(event) { ... }
...
return <Router onNavigate={onNavigate} onCancel={onCancel} />
}
If a component does not want to specify any routing behaviour, but still wants to participate in the navigation callbacks from any child router, it can use the route-less Router exported from react-sprout.
import { Router } from 'react-sprout'
function Application() {
function onNavigate(event) { ... }
function onCancel(event) { ... }
...
return (
<Router onNavigate={onNavigate} onCancel={onCancel}>
...
</Router>
)
}
onNavigate(event)
When a navigation is requested the onNavigate callback is invoked with a navigation event. Use this callback to cancel some or all navigation events by calling preventDefault on the navigation event.
onCancel(event)
When a navigation event was canceled, either in the onNavigate callback or in an event listener for navigate events, the onCancel callback will be invoked.
onNavigateStart(event)
When no callback or event handler has prevented the navigation, the onNavigateStart callback will be invoked.
onError(event, error)
When the action of a POST navigation throws an error, the onError callback will be invoked.
onAbort(event, reason)
When the navigation was aborted, the onAbort callback will be invoked.
A navigation can be aborted automatically by the router because it is interrupted by another navigation. Or navigations can be aborted manually with the useAbort hook.
onNavigateEnd(event, action)
When the navigation was successful, the onNavigateEnd callback will be invoked. The second argument is the result of the navigation's action, if it had one.