Skip to content

Alert

Alerts provide contextual feedback messages for typical user actions with a handful of available and flexible alert messages.

Bootstrap Reference

Bootstrap 5 Alerts


Quick Start

Live Preview
Alert("Your profile has been updated!", variant="success")

Visual Examples & Use Cases

1. Dismissible Alerts

Allow users to close the alert. This is handled automatically by Bootstrap's JS via FastStrap's dismissible=True.

Code & Output

Live Preview
Alert("Important: Your session expires in 5 minutes.", 
      variant="warning", dismissible=True)

2. Rich Content

Alerts can contain headings, links, and multiple paragraphs.

Live Preview
from fasthtml.common import H4, P, Hr

Alert(
    H4("Well done!", cls="alert-heading"),
    P("Aww yeah, you successfully read this important alert message."),
    Hr(),
    P("Whenever you need to, be sure to use margin utilities to keep things nice and tidy."),
    variant="success"
)

3. Icons

Adding icons to alerts significantly improves user recognition of message status.

Live Preview
Alert(
    " An error occurred while saving.", 
    variant="danger", 
    icon="exclamation-triangle-fill"
)

Practical Functionality

1. HTMX Integration (Auto-remove)

Commonly used for temporary notifications that should disappear after an HTMX update.

# Alert is removed from DOM after being seen (requires custom JS or HTMX trick)
Alert(
    "Saved!", 
    variant="success", 
    hx_get="/clear_notification", 
    hx_trigger="load delay:3s" # Disappears after 3 seconds
)

Advanced Customization

1. CSS Variables

CSS Variable Description
--bs-alert-bg Background color.
--bs-alert-color Text color.
--bs-alert-border-color Border color.
--bs-alert-padding-x Padding.
--bs-alert-link-color Color for <A> tags inside.

Parameter Reference

FastStrap Param Type Bootstrap Class Description
variant str .alert-{variant} Color theme.
dismissible bool .alert-dismissible Adds a close button.
icon str - Bootstrap icon name to prepend.

faststrap.components.feedback.alert.Alert(*children, variant=None, dismissible=None, heading=None, heading_cls=None, **kwargs)

Bootstrap Alert component for contextual feedback messages.

Parameters:

Name Type Description Default
*children Any

Alert content

()
variant VariantType | None

Bootstrap color variant

None
dismissible bool | None

Add close button to dismiss alert

None
heading Any | None

Optional heading text or element

None
heading_cls str | None

CSS class for heading

None
**kwargs Any

Additional HTML attributes (cls, id, hx-, data-, etc.)

{}

Returns:

Type Description
Div

FastHTML Div element with alert classes

Source code in src/faststrap/components/feedback/alert.py
@register(category="feedback", requires_js=True)
def Alert(
    *children: Any,
    variant: VariantType | None = None,
    dismissible: bool | None = None,
    heading: Any | None = None,
    heading_cls: str | None = None,
    **kwargs: Any,
) -> Div:
    """Bootstrap Alert component for contextual feedback messages.

    Args:
        *children: Alert content
        variant: Bootstrap color variant
        dismissible: Add close button to dismiss alert
        heading: Optional heading text or element
        heading_cls: CSS class for heading
        **kwargs: Additional HTML attributes (cls, id, hx-*, data-*, etc.)

    Returns:
        FastHTML Div element with alert classes
    """
    # Resolve API defaults
    cfg = resolve_defaults(
        "Alert", variant=variant, dismissible=dismissible, heading_cls=heading_cls
    )

    c_variant = cfg.get("variant", "primary")
    c_dismissible = cfg.get("dismissible", False)
    c_heading_cls = cfg.get("heading_cls", "alert-heading h4")

    # Build base classes
    classes = ["alert", f"alert-{c_variant}"]

    # Add dismissible class if needed
    if c_dismissible:
        classes.append("alert-dismissible fade show")

    # Merge with user classes
    user_cls = kwargs.pop("cls", "")
    all_classes = merge_classes(" ".join(classes), user_cls)

    # Build attributes
    attrs: dict[str, Any] = {"cls": all_classes, "role": "alert"}

    # Convert remaining kwargs
    attrs.update(convert_attrs(kwargs))

    # Build content
    content = []

    # Add heading if provided
    if heading:
        if isinstance(heading, (str, bytes)):
            content.append(Div(heading, cls=c_heading_cls))
        else:
            content.append(heading)

    # Add main content
    content.extend(children)

    # Add close button if dismissible
    if c_dismissible:
        close_btn = Button(
            type="button",
            cls="btn-close",
            data_bs_dismiss="alert",
            aria_label="Close",
        )
        content.append(close_btn)

    return Div(*content, **attrs)