BlazorComponentUtilities 1.8.0

.NET Standard 2.0
NuGet\Install-Package BlazorComponentUtilities -Version 1.8.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
dotnet add package BlazorComponentUtilities --version 1.8.0
<PackageReference Include="BlazorComponentUtilities" Version="1.8.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add BlazorComponentUtilities --version 1.8.0
#r "nuget: BlazorComponentUtilities, 1.8.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install BlazorComponentUtilities as a Cake Addin
#addin nuget:?package=BlazorComponentUtilities&version=1.8.0

// Install BlazorComponentUtilities as a Cake Tool
#tool nuget:?package=BlazorComponentUtilities&version=1.8.0

CSS & Style Builder Pattern

Read the full API docs in the Wiki section

When building complex components for ASP.NET Razor Components there are often CSS classes generated by multiple factors. Styles can often be added by system & component state, public parameters, and static base CSS classes. Combining many CSS classes together doesn't scale well, and when components get large it can be tough to reason about. The CSS builder pattern fixes this problem by offering a easy to repeat, easy to read pattern to use across components in a project. A clean code approach to conditional CSS in Razor Components.

The problem

Given the component below, the Tab's CSS class is set by multiple sources. The component has paramater UserCss which can be set at externally. A base CSS class bl-nav-link which does not change. Two state based CSS classes bl-active and bl-disabled which are dependent on if the Tab is active or disabled. Rendering for the CSS class is spread across multiple concerns and is hard to maintain.


<Tab UserCss="my-class" Disabled=true >...</Tab>

Component Source Markup

<li class="bl-nav-item">
    <a onclick=@Activate class="bl-nav-link @ActiveCssClass @DisabledCssClass" role="button">

Component Source Logic

[Parameter] string UserCss = String.Empty;
protected string ActiveCssClass => IsActive ? "bl-active" : String.Empty;
protected string DisabledCssClass => Disabled ? "bl-disabled" : String.Empty;

The Solution

Using the CSS Builder pattern we can clean up the code and move everything to a single concern. Refactoring the component, we move all of the CSS code to the components logic. In the OnParameterSet lifecycle method, we condense all of the CSS responsibilities into a single variable ClassToRender (this name variable is optional). Next, using the CssBuilder we define what classes should be added to the builder and when they should be rendered. The pattern is as follows AddClass the CSS class and the condition when it should appear AddClass(value, when: bool). If the value is static, we can discard the when parameter. Finally, Build is called. All CSS classes are then combined into a single string, properly spaced and trimmed.

The refactored code becomes:

Component Source Markup (refactor)

<li class="bl-nav-item">
    <a onclick=@Activate class="@ClassToRender" role="button">

Component Source Logic (refactor)

protected override void OnParametersSet()
    ClassToRender = new CssBuilder(UserCss)
                        .AddClass("bl-active", when: IsActive)
                        .AddClass("bl-disabled", when: Disabled)

Component Source Logic (refactor with SetPrefix)

protected override void OnParametersSet()
    ClassToRender = new CssBuilder(UserCss)
                        .AddClass("active", when: IsActive)
                        .AddClass("disabled", when: Disabled)

Dynamic values

If you encounter a dynamic value where some string is added to a CSS class name, we can easily handle this as well. Consider the CSS namespace bl- must be prefixed to a value SomeValue supplied by the component state or user input. This is easily handled with string interpolation ${var}.

protected override void OnParametersSet()
    ClassToRender = new CssBuilder(UserCss)
                        .AddClass("bl-active", when: IsActive)
                        .AddClass("bl-disabled", when: Disabled)
			.AddClass("bl-${SomeValue}", when: IsConditionMet)

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.

<MyComponent class="custom-value">

<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);

Func When

Func<bool> is also accepted as an arguement for the when parameter. This allows either inline functions or named functions to be called directly.

protected override void OnParametersSet()
    ClassToRender = new CssBuilder(UserCss)
			.AddClass("bl-foo", when: ()=> 
			   !string.IsNullOrEmpty(Foo) ||
                           !Disabled ||
                        .AddClass("bl-active", when: IsActive)
                        .AddClass("bl-disabled", when: Disabled)

Named function, example.

bool HasMeaningfulName() => !string.IsNullOrEmpty(Foo) || !Disabled || IsActive);

protected override void OnParametersSet()
    ClassToRender = new CssBuilder(UserCss)
			.AddClass("bl-foo", when: HasMeaningfulName)
                        .AddClass("bl-active", when: IsActive)
                        .AddClass("bl-disabled", when: Disabled)

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.

<div class="">

<div class="@CssClass">

@code {

    //string CssClass => new CssBuilder().AddClassFromAttributes(attributes).Build();
    string CssClass => new CssBuilder().AddClassFromAttributes(attributes).NullIfEmpty();
Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows
.NET Core netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1
.NET Standard netstandard2.0 netstandard2.1
.NET Framework net461 net462 net463 net47 net471 net472 net48
MonoAndroid monoandroid
MonoMac monomac
MonoTouch monotouch
Tizen tizen40 tizen60
Xamarin.iOS xamarinios
Xamarin.Mac xamarinmac
Xamarin.TVOS xamarintvos
Xamarin.WatchOS xamarinwatchos
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages (15)

Showing the top 5 NuGet packages that depend on BlazorComponentUtilities:

Package Downloads

A bootstrap 5 component library for Blazor


A collection of loading indicators animated with CSS for Blazor. Spinkit also includes the SpinLoader component with templates for handling null values during async operations. Spinkit includes CSS from the Spinkit project by Tobias Ahlin


A collection of Blazor components based on the default controls that ship with ASP.NET Web Forms


Package Description


A Material Design Component library for Blazor

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.8.0 21,139 12/10/2021
1.7.1 35,078 7/30/2021
1.7.0 11,096 6/14/2021
1.6.0 538,349 1/24/2020
1.5.0 335 1/23/2020
1.4.0 371 1/23/2020
1.3.1 560 1/16/2020
1.3.0 13,875 1/5/2020
1.2.1 473 1/4/2020
1.1.0 47,318 7/10/2019
1.0.0 655 4/11/2019

Fixed null ref error when using AddClassFromAttributes and passing a null attribute value.
Fixed trivial performance issue with redundant assignment when building strings
Added SetPrefix method to reduce reptititive class prefixing
Added Func<string> value overload for ValueBuilder
     Added Func<string> value overload for StyleBuilder
     Minor performance improvements for .Add*Attributes
     Added ValueBuilder for complex styles
      Updated /// docs
     Added utlitiy mehtod for Attribute Splatting.
     Added utility method for returning null for empty strings. This is useful for splatting scenarios.
     Added utility method for starting off new builders.