link.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //! How to use links in Dioxus
  2. //!
  3. //! The `router` crate gives us a `Link` component which is a much more powerful version of the standard HTML link.
  4. //! However, you can use the traditional `<a>` tag if you want to build your own `Link` component.
  5. //!
  6. //! The `Link` component integrates with the Router and is smart enough to detect if the link is internal or external.
  7. //! It also allows taking any `Route` as a target, making your links typesafe
  8. use dioxus::prelude::*;
  9. fn main() {
  10. launch(app);
  11. }
  12. fn app() -> Element {
  13. rsx! (
  14. style { {include_str!("./assets/links.css")} }
  15. Router::<Route> {}
  16. )
  17. }
  18. #[derive(Routable, Clone)]
  19. #[rustfmt::skip]
  20. enum Route {
  21. #[layout(Header)]
  22. #[route("/")]
  23. Home {},
  24. #[route("/default-links")]
  25. DefaultLinks {},
  26. #[route("/settings")]
  27. Settings {},
  28. }
  29. #[component]
  30. fn Header() -> Element {
  31. rsx! {
  32. h1 { "Your app here" }
  33. nav { id: "nav",
  34. Link { to: Route::Home {}, "home" }
  35. Link { to: Route::DefaultLinks {}, "default links" }
  36. Link { to: Route::Settings {}, "settings" }
  37. }
  38. Outlet::<Route> {}
  39. }
  40. }
  41. #[component]
  42. fn Home() -> Element {
  43. rsx!( h1 { "Home" } )
  44. }
  45. #[component]
  46. fn Settings() -> Element {
  47. rsx!( h1 { "Settings" } )
  48. }
  49. #[component]
  50. fn DefaultLinks() -> Element {
  51. rsx! {
  52. // Just some default links
  53. div { id: "external-links",
  54. // This link will open in a webbrowser
  55. a { href: "http://dioxuslabs.com/", "Default link - links outside of your app" }
  56. // This link will do nothing - we're preventing the default behavior
  57. // It will just log "Hello Dioxus" to the console
  58. a {
  59. href: "http://dioxuslabs.com/",
  60. prevent_default: "onclick",
  61. onclick: |_| println!("Hello Dioxus"),
  62. "Custom event link - links inside of your app"
  63. }
  64. }
  65. }
  66. }