2.9 KiB
Programmatic Navigation
Sometimes we want our application to navigate to another page without having the user click on a link. This is called programmatic navigation.
Acquiring a Navigator
To use programmatic navigation, we first have to acquire a Navigator. For
that purpose we can use the use_navigate hook.
# // Hidden lines (like this one) make the documentation tests work.
# extern crate dioxus;
use dioxus::prelude::*;
# extern crate dioxus_router;
use dioxus_router::prelude::*;
fn Content(cx: Scope) -> Element {
let nav = use_navigate(&cx).expect("called inside a router");
// ...
# unimplemented!()
}
Triggering a Navigation
We can use the Navigator to trigger four different kinds of navigation:
pushwill navigate to the target. It works like a regular anchor tag.replaceworks likepush, except that it replaces the current history entry instead of adding a new one. This means the prior page cannot be restored with the browsers back button.Go backworks like the browsers back button.Go forwardworks like the browsers forward button (the opposite of the back button).
# // Hidden lines (like this one) make the documentation tests work.
# extern crate dioxus;
# use dioxus::prelude::*;
# extern crate dioxus_router;
# use dioxus_router::prelude::*;
#
fn Content(cx: Scope) -> Element {
let nav = use_navigate(&cx).expect("called inside a router");
// push
nav.push("/target");
// replace
nav.replace("/target");
// go back
nav.go_back();
// go forward
nav.go_forward();
// ...
# unimplemented!()
}
You might have noticed that, like Link, the Navigators push and
replace functions take a NavigationTarget. This means we can use
Internal, Named and External.
External Navigation Targets
Unlike a Link, the Navigator cannot rely on the browser (or webview) to
handle navigation to external targets via a generated anchor element.
This means, that under certain conditions, navigation to external targets can fail. See the chapter about external navigation failures for more details.