dioxus_router/hooks/
use_route.rs

1use crate::prelude::*;
2use crate::utils::use_router_internal::use_router_internal;
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 [`Router`] component.
10///
11/// # Example
12/// ```rust
13/// # use dioxus::prelude::*;
14/// # use dioxus_router::{prelude::*};
15///
16/// #[derive(Clone, Routable)]
17/// enum Route {
18///     #[route("/")]
19///     Index {},
20/// }
21///
22/// #[component]
23/// fn App() -> Element {
24///     rsx! {
25///         h1 { "App" }
26///         Router::<Route> {}
27///     }
28/// }
29///
30/// #[component]
31/// fn Index() -> Element {
32///     let path: Route = use_route();
33///     rsx! {
34///         h2 { "Current Path" }
35///         p { "{path}" }
36///     }
37/// }
38/// #
39/// # let mut vdom = VirtualDom::new(App);
40/// # vdom.rebuild_in_place();
41/// # assert_eq!(dioxus_ssr::render(&vdom), "<h1>App</h1><h2>Current Path</h2><p>/</p>")
42/// ```
43#[doc(alias = "use_url")]
44#[must_use]
45pub fn use_route<R: Routable + Clone>() -> R {
46    match use_router_internal() {
47        Some(r) => r.current(),
48        None => {
49            panic!("`use_route` must be called in a descendant of a Router component")
50        }
51    }
52}