use_navigator.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use dioxus::prelude::ScopeState;
  2. use crate::prelude::{Navigator, RouterContext};
  3. /// A hook that provides access to the navigator to change the router history. Unlike [`use_router`], this hook will not cause a rerender when the current route changes
  4. ///
  5. /// > The Routable macro will define a version of this hook with an explicit type.
  6. ///
  7. /// ```rust
  8. /// # use dioxus::prelude::*;
  9. /// # use dioxus_router::prelude::*;
  10. /// #[derive(Clone, Routable)]
  11. /// enum Route {
  12. /// #[route("/")]
  13. /// Index {},
  14. /// #[route("/:id")]
  15. /// Dynamic { id: usize },
  16. /// }
  17. ///
  18. /// #[component]
  19. /// fn App(cx: Scope) -> Element {
  20. /// render! {
  21. /// Router::<Route> {}
  22. /// }
  23. /// }
  24. ///
  25. /// #[component]
  26. /// fn Index(cx: Scope) -> Element {
  27. /// let navigator = use_navigator(&cx);
  28. ///
  29. /// render! {
  30. /// button {
  31. /// onclick: move |_| { navigator.push(Route::Dynamic { id: 1234 }); },
  32. /// "Go to /1234"
  33. /// }
  34. /// }
  35. /// }
  36. ///
  37. /// #[component]
  38. /// fn Dynamic(cx: Scope, id: usize) -> Element {
  39. /// render! {
  40. /// p {
  41. /// "Current ID: {id}"
  42. /// }
  43. /// }
  44. /// }
  45. ///
  46. /// # let mut vdom = VirtualDom::new(App);
  47. /// # let _ = vdom.rebuild();
  48. /// ```
  49. #[must_use]
  50. pub fn use_navigator(cx: &ScopeState) -> &Navigator {
  51. &*cx.use_hook(|| {
  52. let router = cx
  53. .consume_context::<RouterContext>()
  54. .expect("Must be called in a descendant of a Router component");
  55. Navigator(router)
  56. })
  57. }