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