1
0

use_route.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. use crate::prelude::*;
  2. use crate::utils::use_router_internal::use_router_internal;
  3. /// A hook that provides access to information about the current routing location.
  4. ///
  5. /// > The Routable macro will define a version of this hook with an explicit type.
  6. ///
  7. /// # Panic
  8. /// - When the calling component is not nested within a [`Router`] component.
  9. ///
  10. /// # Example
  11. /// ```rust
  12. /// # use dioxus::prelude::*;
  13. /// # use dioxus_router::{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. /// # let _ = vdom.rebuild();
  40. /// # assert_eq!(dioxus_ssr::render(&vdom), "<h1>App</h1><h2>Current Path</h2><p>/</p>")
  41. /// ```
  42. #[must_use]
  43. pub fn use_route<R: Routable + Clone>() -> R {
  44. match use_router_internal() {
  45. Some(r) => r.current(),
  46. None => {
  47. panic!("`use_route` must be called in a descendant of a Router component")
  48. }
  49. }
  50. }