link.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use crate::RouterService;
  2. use dioxus::Attribute;
  3. use dioxus_core as dioxus;
  4. use dioxus_core::prelude::*;
  5. use dioxus_core_macro::{format_args_f, rsx, Props};
  6. use dioxus_html as dioxus_elements;
  7. #[derive(Props)]
  8. pub struct LinkProps<'a> {
  9. to: &'a str,
  10. /// The url that gets pushed to the history stack
  11. ///
  12. /// You can either put in your own inline method or just autoderive the route using `derive(Routable)`
  13. ///
  14. /// ```rust, ignore
  15. ///
  16. /// Link { to: Route::Home, href: |_| "home".to_string() }
  17. ///
  18. /// // or
  19. ///
  20. /// Link { to: Route::Home, href: Route::as_url }
  21. ///
  22. /// ```
  23. #[props(default, strip_option)]
  24. href: Option<&'a str>,
  25. #[props(default, strip_option)]
  26. class: Option<&'a str>,
  27. #[props(default, strip_option)]
  28. id: Option<&'a str>,
  29. #[props(default, strip_option)]
  30. title: Option<&'a str>,
  31. children: Element<'a>,
  32. #[props(default)]
  33. attributes: Option<&'a [Attribute<'a>]>,
  34. }
  35. pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
  36. // log::trace!("render Link to {}", cx.props.to);
  37. if let Some(service) = cx.consume_context::<RouterService>() {
  38. return cx.render(rsx! {
  39. a {
  40. href: "{cx.props.to}",
  41. class: format_args!("{}", cx.props.class.unwrap_or("")),
  42. id: format_args!("{}", cx.props.id.unwrap_or("")),
  43. title: format_args!("{}", cx.props.title.unwrap_or("")),
  44. prevent_default: "onclick",
  45. onclick: move |_| service.push_route(cx.props.to),
  46. &cx.props.children
  47. }
  48. });
  49. }
  50. log::warn!(
  51. "Attempted to create a Link to {} outside of a Router context",
  52. cx.props.to,
  53. );
  54. None
  55. }