simple_router.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //! A simple example of a router with a few routes and a nav bar.
  2. use dioxus::prelude::*;
  3. fn main() {
  4. // Launch the router, using our `Route` component as the generic type
  5. // This will automatically boot the app to "/" unless otherwise specified
  6. launch(|| rsx! { Router::<Route> {} });
  7. }
  8. /// By default, the Routable derive will use the name of the variant as the route
  9. /// You can also specify a specific component by adding the Component name to the `#[route]` attribute
  10. #[rustfmt::skip]
  11. #[derive(Routable, Clone, PartialEq)]
  12. enum Route {
  13. // Wrap the app in a Nav layout
  14. #[layout(Nav)]
  15. #[route("/")]
  16. Homepage {},
  17. #[route("/blog/:id")]
  18. Blog { id: String },
  19. }
  20. #[component]
  21. fn Homepage() -> Element {
  22. rsx! {
  23. h1 { "Welcome home" }
  24. }
  25. }
  26. #[component]
  27. fn Blog(id: String) -> Element {
  28. rsx! {
  29. h1 { "How to make: " }
  30. p { "{id}" }
  31. }
  32. }
  33. /// A simple nav bar that links to the homepage and blog pages
  34. ///
  35. /// The `Route` enum gives up typesafe routes, allowing us to rename routes and serialize them automatically
  36. #[component]
  37. fn Nav() -> Element {
  38. rsx! {
  39. nav {
  40. li {
  41. Link { to: Route::Homepage {}, "Go home" }
  42. }
  43. li {
  44. Link {
  45. to: Route::Blog {
  46. id: "Brownies".to_string(),
  47. },
  48. "Learn Brownies"
  49. }
  50. }
  51. li {
  52. Link {
  53. to: Route::Blog {
  54. id: "Cookies".to_string(),
  55. },
  56. "Learn Cookies"
  57. }
  58. }
  59. }
  60. div { Outlet::<Route> {} }
  61. }
  62. }