use_router.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use dioxus::prelude::ScopeState;
  2. use crate::{
  3. prelude::GenericRouterContext, routable::Routable,
  4. utils::use_router_internal::use_router_internal,
  5. };
  6. /// A hook that provides access to information about the router. The Router will define a version of this hook with an explicit type.
  7. ///
  8. /// ```rust
  9. /// # use dioxus::prelude::*;
  10. /// # use dioxus_router::prelude::*;
  11. /// # use serde::{Deserialize, Serialize};
  12. /// #[derive(Clone, Serialize, Deserialize, Routable)]
  13. /// enum Route {
  14. /// #[route("/")]
  15. /// Index {},
  16. /// #[route("/:id")]
  17. /// Dynamic { id: usize },
  18. /// }
  19. ///
  20. /// fn App(cx: Scope) -> Element {
  21. /// render! {
  22. /// Router {}
  23. /// }
  24. /// }
  25. ///
  26. /// #[inline_props]
  27. /// fn Index(cx: Scope) -> Element {
  28. /// let router = use_router(&cx);
  29. ///
  30. /// render! {
  31. /// button {
  32. /// onclick: move |_| { router.push(Route::Dynamic { id: 1234 }); },
  33. /// "Go to /1234"
  34. /// }
  35. /// }
  36. /// }
  37. ///
  38. /// #[inline_props]
  39. /// fn Dynamic(cx: Scope, id: usize) -> Element {
  40. /// render! {
  41. /// p {
  42. /// "Current ID: {id}"
  43. /// }
  44. /// }
  45. /// }
  46. ///
  47. /// # let mut vdom = VirtualDom::new(App);
  48. /// # let _ = vdom.rebuild();
  49. /// ```
  50. pub fn use_generic_router<R: Routable + Clone>(cx: &ScopeState) -> &GenericRouterContext<R> {
  51. use_router_internal(cx)
  52. .as_ref()
  53. .expect("use_route must have access to a router")
  54. }