link.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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: &str = asset!("./examples/assets/links.css");
  10. fn main() {
  11. launch(app);
  12. }
  13. fn app() -> Element {
  14. rsx! (
  15. head::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. prevent_default: "onclick",
  62. onclick: |_| println!("Hello Dioxus"),
  63. "Custom event link - links inside of your app"
  64. }
  65. }
  66. }
  67. }