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