Skip to main content

dioxus_bootstrap_css/
badge.rs

1use dioxus::prelude::*;
2
3use crate::types::Color;
4
5/// Bootstrap Badge component.
6///
7/// # Bootstrap HTML → Dioxus
8///
9/// | HTML | Dioxus |
10/// |---|---|
11/// | `<span class="badge text-bg-primary">New</span>` | `Badge { color: Color::Primary, "New" }` |
12/// | `<span class="badge rounded-pill text-bg-danger">99+</span>` | `Badge { color: Color::Danger, pill: true, "99+" }` |
13/// | `<span class="badge text-bg-secondary" role="button">Open</span>` | `Badge { color: Color::Secondary, onclick: move |_| {}, "Open" }` |
14///
15/// ```rust,no_run
16/// # use dioxus::prelude::*;
17/// # use dioxus_bootstrap_css::prelude::*;
18/// # fn _doctest() -> Element {
19/// rsx! {
20///     Badge { color: Color::Primary, "New" }
21///     Badge { color: Color::Danger, pill: true, "99+" }
22///     // Inside a heading
23///     h1 { "Messages " Badge { color: Color::Info, "4" } }
24/// }
25/// # }
26/// ```
27#[derive(Clone, PartialEq, Props)]
28pub struct BadgeProps {
29    /// Badge color variant.
30    #[props(default = Color::Primary)]
31    pub color: Color,
32    /// Use pill (rounded) style.
33    #[props(default)]
34    pub pill: bool,
35    /// Additional CSS classes.
36    #[props(default)]
37    pub class: String,
38    /// Click event handler.
39    #[props(default)]
40    pub onclick: Option<EventHandler<MouseEvent>>,
41    /// Any additional HTML attributes.
42    #[props(extends = GlobalAttributes)]
43    attributes: Vec<Attribute>,
44    /// Child elements.
45    pub children: Element,
46}
47
48#[component]
49pub fn Badge(props: BadgeProps) -> Element {
50    let pill = if props.pill { " rounded-pill" } else { "" };
51    let full_class = if props.class.is_empty() {
52        format!("badge text-bg-{}{pill}", props.color)
53    } else {
54        format!("badge text-bg-{}{pill} {}", props.color, props.class)
55    };
56
57    rsx! {
58        span {
59            class: "{full_class}",
60            onclick: move |evt| {
61                if let Some(handler) = &props.onclick {
62                    handler.call(evt);
63                }
64            },
65            ..props.attributes,
66            {props.children}
67        }
68    }
69}