simple_router.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. dioxus::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! { h1 { "Welcome home" } }
  23. }
  24. #[component]
  25. fn Blog(id: String) -> Element {
  26. rsx! {
  27. h1 { "How to make: " }
  28. p { "{id}" }
  29. }
  30. }
  31. /// A simple nav bar that links to the homepage and blog pages
  32. ///
  33. /// The `Route` enum gives up typesafe routes, allowing us to rename routes and serialize them automatically
  34. #[component]
  35. fn Nav() -> Element {
  36. rsx! {
  37. nav {
  38. li {
  39. Link { to: Route::Homepage {}, "Go home" }
  40. }
  41. li {
  42. Link {
  43. to: Route::Blog {
  44. id: "Brownies".to_string(),
  45. },
  46. onclick: move |_| { println!("Clicked on Brownies") },
  47. "Learn Brownies"
  48. }
  49. }
  50. li {
  51. Link {
  52. to: Route::Blog {
  53. id: "Cookies".to_string(),
  54. },
  55. "Learn Cookies"
  56. }
  57. }
  58. }
  59. div { Outlet::<Route> {} }
  60. }
  61. }