link.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. const STYLE: Asset = asset!("/examples/assets/links.css");
  10. fn main() {
  11. dioxus::launch(app);
  12. }
  13. fn app() -> Element {
  14. rsx! (
  15. document::Link { rel: "stylesheet", href: STYLE }
  16. Router::<Route> {}
  17. )
  18. }
  19. #[derive(Routable, Clone)]
  20. #[rustfmt::skip]
  21. enum Route {
  22. #[layout(Header)]
  23. #[route("/")]
  24. Home {},
  25. #[route("/default-links")]
  26. DefaultLinks {},
  27. #[route("/settings")]
  28. Settings {},
  29. }
  30. #[component]
  31. fn Header() -> Element {
  32. rsx! {
  33. h1 { "Your app here" }
  34. nav { id: "nav",
  35. Link { to: Route::Home {}, "home" }
  36. Link { to: Route::DefaultLinks {}, "default links" }
  37. Link { to: Route::Settings {}, "settings" }
  38. }
  39. Outlet::<Route> {}
  40. }
  41. }
  42. #[component]
  43. fn Home() -> Element {
  44. rsx!( h1 { "Home" } )
  45. }
  46. #[component]
  47. fn Settings() -> Element {
  48. rsx!( h1 { "Settings" } )
  49. }
  50. #[component]
  51. fn DefaultLinks() -> Element {
  52. rsx! {
  53. // Just some default links
  54. div { id: "external-links",
  55. // This link will open in a webbrowser
  56. a { href: "http://dioxuslabs.com/", "Default link - links outside of your app" }
  57. // This link will do nothing - we're preventing the default behavior
  58. // It will just log "Hello Dioxus" to the console
  59. a {
  60. href: "http://dioxuslabs.com/",
  61. onclick: |event| {
  62. event.prevent_default();
  63. println!("Hello Dioxus")
  64. },
  65. "Custom event link - links inside of your app"
  66. }
  67. }
  68. }
  69. }