dioxus/examples/link.rs

82 lines
2.1 KiB
Rust
Raw Normal View History

2024-02-14 20:33:07 +00:00
//! How to use links in Dioxus
//!
//! The `router` crate gives us a `Link` component which is a much more powerful version of the standard HTML link.
//! However, you can use the traditional `<a>` tag if you want to build your own `Link` component.
//!
//! The `Link` component integrates with the Router and is smart enough to detect if the link is internal or external.
//! It also allows taking any `Route` as a target, making your links typesafe
2022-01-18 01:19:12 +00:00
use dioxus::prelude::*;
const STYLE: &str = asset!("./examples/assets/links.css");
2022-01-18 01:19:12 +00:00
fn main() {
launch(app);
2022-01-18 01:19:12 +00:00
}
2024-02-14 20:33:07 +00:00
fn app() -> Element {
2024-01-16 19:18:46 +00:00
rsx! (
head::Link { rel: "stylesheet", href: STYLE }
2024-02-14 20:33:07 +00:00
Router::<Route> {}
2024-01-14 05:12:21 +00:00
)
2022-01-18 01:19:12 +00:00
}
2022-12-16 10:55:20 +00:00
2023-06-02 17:33:47 +00:00
#[derive(Routable, Clone)]
#[rustfmt::skip]
enum Route {
#[layout(Header)]
#[route("/")]
Home {},
2024-02-14 20:33:07 +00:00
#[route("/default-links")]
DefaultLinks {},
2023-06-02 17:33:47 +00:00
#[route("/settings")]
Settings {},
}
#[component]
fn Header() -> Element {
2024-01-16 19:18:46 +00:00
rsx! {
2023-06-02 17:33:47 +00:00
h1 { "Your app here" }
2024-02-14 20:33:07 +00:00
nav { id: "nav",
Link { to: Route::Home {}, "home" }
Link { to: Route::DefaultLinks {}, "default links" }
Link { to: Route::Settings {}, "settings" }
2023-06-02 17:33:47 +00:00
}
2023-07-26 01:14:48 +00:00
Outlet::<Route> {}
2023-06-02 17:33:47 +00:00
}
}
#[component]
fn Home() -> Element {
2024-01-16 19:18:46 +00:00
rsx!( h1 { "Home" } )
2022-12-16 10:55:20 +00:00
}
#[component]
fn Settings() -> Element {
2024-01-16 19:18:46 +00:00
rsx!( h1 { "Settings" } )
2022-12-16 10:55:20 +00:00
}
2024-02-14 20:33:07 +00:00
#[component]
fn DefaultLinks() -> Element {
rsx! {
// Just some default links
div { id: "external-links",
// This link will open in a webbrowser
a { href: "http://dioxuslabs.com/", "Default link - links outside of your app" }
// This link will do nothing - we're preventing the default behavior
// It will just log "Hello Dioxus" to the console
a {
href: "http://dioxuslabs.com/",
onclick: |event| {
event.prevent_default();
println!("Hello Dioxus")
},
2024-02-14 20:33:07 +00:00
"Custom event link - links inside of your app"
}
}
}
}