Skip to content

CssBuilder.AddClassFromAttributes Method

Ed Charbeneau edited this page Jan 16, 2020 · 2 revisions

AddClassFromAttributes(IReadOnlyDictionary<string, object> additionalAttributes)

Adds a conditional CSS Class when it exists in a dictionary to the builder with space separator. Null safe operation checks for the the class dictionary key internally.

public CssBuilder AddClassFromAttributes(IReadOnlyDictionary<string, object> additionalAttributes)

Example: Attribute Splatting

If you encounter dynamic values due to attribute splatting, we can easily handle this as well. Consider the senario where we need to merge a splatted CSS attribute while preserving default values.

<!-- API -->
<MyComponent class="custom-value">
<!-- Output -->
<div class="my-base custom-value">
<div @attributes="AdditionalAttributes" class="@CssClass">

@code {

    [Parameter(CaptureUnmatchedValues = true)]
    public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; } = new Dictionary<string, Object>();

    CssBuilder CssClass => new CssBuilder("my-base").AddClassFromAttributes(attributes);
}

Example: Removing Unused Attributes

When using dynamic attributes may result in empty attribute. When Blazor renders an attribute that has an empty string value, it will result in an empty attribute tag. However, if the value is null the attribute will be excluded. When an empty attribute is expected, the extension method NullIfEmpty can be used to clean up the resulting markup. Note: This method is only necessary when no default value is supplied. Ex: new CssBuilder() or CssBuilder().Empty(). Forgetting to call NullIfEmpty should not have any impact on the UI.

<!-- Output with Empty String -->
<div class="">

<!-- Output with null -->
<div>
<div class="@CssClass">

@code {

    //string CssClass => new CssBuilder().AddClassFromAttributes(attributes).Build();
    string CssClass => new CssBuilder().AddClassFromAttributes(attributes).NullIfEmpty();
}