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///
14/// ```rust,no_run
15/// rsx! {
16///     Badge { color: Color::Primary, "New" }
17///     Badge { color: Color::Danger, pill: true, "99+" }
18///     // Inside a heading
19///     h1 { "Messages " Badge { color: Color::Info, "4" } }
20/// }
21/// ```
22#[derive(Clone, PartialEq, Props)]
23pub struct BadgeProps {
24    /// Badge color variant.
25    #[props(default = Color::Primary)]
26    pub color: Color,
27    /// Use pill (rounded) style.
28    #[props(default)]
29    pub pill: bool,
30    /// Additional CSS classes.
31    #[props(default)]
32    pub class: String,
33    /// Any additional HTML attributes.
34    #[props(extends = GlobalAttributes)]
35    attributes: Vec<Attribute>,
36    /// Child elements.
37    pub children: Element,
38}
39
40#[component]
41pub fn Badge(props: BadgeProps) -> Element {
42    let pill = if props.pill { " rounded-pill" } else { "" };
43    let full_class = if props.class.is_empty() {
44        format!("badge text-bg-{}{pill}", props.color)
45    } else {
46        format!("badge text-bg-{}{pill} {}", props.color, props.class)
47    };
48
49    rsx! {
50        span { class: "{full_class}", ..props.attributes, {props.children} }
51    }
52}