Bringing Back the Class Attribute for Your Blazor Components

Blazor, like many other client-side web UI frameworks, is primarily used to create and render components to the web browser. A component is essentially a custom HTML element that we can design, build, and reuse.

One of the most familiar attributes of HTML elements is the class attribute, which allows us to apply styles using a list of CSS classes.

Blazor, however, does not provide support for native HTML attributes. If you want to apply an attribute to your component, you must first define it as a parameter.

In practice, this means that applying the class attribute to a Blazor component will throw an InvalidOperationException at runtime, as Blazor fails to match the “class” name to a parameter in our component.

But what if we want to let others apply one or more CSS classes to our component?

The answer is simple: we use our own class attribute.

The way I suggest doing it is by defining a parameter named CssClass. This seems to be an unspoken pattern in both Microsoft’s own native components and in other third-party component libraries.

To illustrate, let’s say we are writing a simple button component named Button.razor.

First we define the new CssClass parameter in our code block:

[Parameter]
public string CssClass { get; set; }

[Parameter]
public string Text { get; set; }

Then we render this parameter to the class attribute inside our markup using a Razor expression:

<button class="btn @CssClass">@Text</button>

Now we can use this element from within our application and style it using classes as naturally as any other HTML element:

<Button CssClass="bg-red text-white" Text="Big Red Button, Do Not Click!"></Button>

You can apply this pattern and you’ll find that it’s a pretty clean way to bring back the class attribute for your Blazor components.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s