dioxus_router/hooks/
use_route.rs

1use crate::utils::use_router_internal::use_router_internal;
2use crate::Routable;
3
4/// A hook that provides access to information about the current routing location.
5///
6/// > The Routable macro will define a version of this hook with an explicit type.
7///
8/// # Panic
9/// - When the calling component is not nested within a [`crate::Router`] component.
10///
11/// # Example
12/// ```rust
13/// # use dioxus::prelude::*;
14///
15/// #[derive(Clone, Routable)]
16/// enum Route {
17///     #[route("/")]
18///     Index {},
19/// }
20///
21/// #[component]
22/// fn App() -> Element {
23///     rsx! {
24///         h1 { "App" }
25///         Router::<Route> {}
26///     }
27/// }
28///
29/// #[component]
30/// fn Index() -> Element {
31///     let path: Route = use_route();
32///     rsx! {
33///         h2 { "Current Path" }
34///         p { "{path}" }
35///     }
36/// }
37/// #
38/// # let mut vdom = VirtualDom::new(App);
39/// # vdom.rebuild_in_place();
40/// # assert_eq!(dioxus_ssr::render(&vdom), "<h1>App</h1><h2>Current Path</h2><p>/</p>")
41/// ```
42#[doc(alias = "use_url")]
43#[must_use]
44pub fn use_route<R: Routable + Clone>() -> R {
45    match use_router_internal() {
46        Some(r) => r.current(),
47        None => {
48            panic!("`use_route` must be called in a descendant of a Router component")
49        }
50    }
51}