yew_bootstrap/component/
link.rs

1use crate::util::Color;
2use yew::prelude::*;
3
4/// # Link component
5/// Link component rendered as `<a/>` component. This link can contain
6/// any element.
7///
8/// See [LinkProps] for a listing of properties.
9///
10/// ## Example
11/// Example of link:
12///
13/// ```rust
14/// use yew::prelude::*;
15/// use yew_bootstrap::component::Link;
16/// use yew_bootstrap::util::Color;
17/// fn test() -> Html {
18///     html!{
19///         <Link style={Color::Primary} stretched={ true } text={ "Link text" } url={ "https://github.com/isosphere/yew-bootstrap/" }/>
20///     }
21/// }
22/// ```
23pub struct Link {}
24
25/// Properties for [Link]
26#[derive(Properties, Clone, PartialEq)]
27pub struct LinkProps {
28    /// CSS class
29    #[prop_or_default]
30    pub class: String,
31
32    /// Children
33    #[prop_or_default]
34    pub children: Children,
35
36    /// Stretched if true, making its parent container clickable
37    #[prop_or_default]
38    pub stretched: bool,
39
40    /// Color style
41    #[prop_or_default]
42    pub style: Option<Color>,
43
44    /// URL to direct to when the link is clicked
45    #[prop_or_default]
46    pub url: Option<AttrValue>,
47
48    /// Target frame or window ID for the link
49    #[prop_or_default]
50    pub target: Option<AttrValue>,
51
52    /// Optional text for the link
53    #[prop_or_default]
54    pub text: String,
55
56    /// Reference to the [NodeRef] of the link's underlying `<a>` element.
57    ///
58    /// Used by components which add custom event handlers directly to the DOM.
59    ///
60    /// See [*Node Refs* in the Yew documentation][0] for more information.
61    ///
62    /// [0]: https://yew.rs/docs/concepts/function-components/node-refs
63    #[prop_or_default]
64    pub node_ref: NodeRef,
65}
66
67impl Component for Link {
68    type Message = ();
69    type Properties = LinkProps;
70
71    fn create(_ctx: &Context<Self>) -> Self {
72        Self {}
73    }
74
75    fn view(&self, ctx: &Context<Self>) -> Html {
76        let props = ctx.props();
77        let mut classes = Classes::new();
78        if let Some(style) = props.style.clone() {
79            classes.push(format!("link-{}", style));
80        }
81        if props.stretched {
82            classes.push("stretched-link");
83        }
84        classes.push(props.class.clone());
85
86        html! {
87            <a
88                class={classes}
89                role={props.url.is_none().then_some("button")}
90                href={props.url.clone()}
91                target={props.target.clone()}
92                ref={props.node_ref.clone()}
93            >
94                { &props.text }
95                { for props.children.iter() }
96            </a>
97        }
98    }
99}