yew_router_nested/components/
router_link.rs

1//! A component wrapping an `<a>` tag that changes the route.
2use crate::{
3    agent::{RouteAgentDispatcher, RouteRequest},
4    route::Route,
5    Switch,
6};
7use std::marker::PhantomData;
8use yew::prelude::*;
9
10use super::{Msg, Props};
11use crate::RouterState;
12use yew::virtual_dom::VNode;
13
14/// An anchor tag Component that when clicked, will navigate to the provided route.
15///
16/// Alias to RouterAnchor.
17#[deprecated(note = "Has been renamed to RouterAnchor")]
18pub type RouterLink<T> = RouterAnchor<T>;
19
20/// An anchor tag Component that when clicked, will navigate to the provided route.
21#[derive(Debug)]
22pub struct RouterAnchor<SW: Switch + PartialEq + Clone + 'static, STATE: RouterState = ()> {
23    router: RouteAgentDispatcher<STATE>,
24    _marker: PhantomData<SW>,
25}
26
27impl<SW: Switch + PartialEq + Clone + 'static, STATE: RouterState> Component
28    for RouterAnchor<SW, STATE>
29{
30    type Message = Msg;
31    type Properties = Props<SW>;
32
33    fn create(_: &Context<Self>) -> Self {
34        let router = RouteAgentDispatcher::new();
35        RouterAnchor {
36            _marker: Default::default(),
37            router,
38        }
39    }
40
41    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
42        match msg {
43            Msg::Clicked => {
44                let route = Route::from(ctx.props().route.clone());
45                self.router.send(RouteRequest::ChangeRoute(route));
46                false
47            }
48        }
49    }
50
51    fn view(&self, ctx: &Context<Self>) -> VNode {
52        #[cfg(feature = "std_web")]
53        use stdweb::web::event::IEvent;
54
55        let route: Route<STATE> = Route::from(ctx.props().route.clone());
56
57        #[cfg(feature = "std_web")]
58        let cb = ctx.link().callback(|event: ClickEvent| {
59            event.prevent_default();
60            Msg::Clicked
61        });
62        #[cfg(feature = "web_sys")]
63        let cb = ctx.link().callback(|event: MouseEvent| {
64            event.prevent_default();
65            Msg::Clicked
66        });
67
68        html! {
69            <a
70                class={ctx.props().classes.clone()}
71                onclick={cb}
72                disabled={ctx.props().disabled}
73                href={route.route}
74            >
75                {
76                    #[allow(deprecated)]
77                    &ctx.props().text
78                }
79                {ctx.props().children.iter().collect::<VNode>()}
80            </a>
81        }
82    }
83}