Skip to main content

Blazor - Cascading Component Attributes

05 Sep 2020 - Cody Merritt Anhorn

When using Blazor you will sometimes need to give a Button some of your own flare, with that comes the problem of mapping all the attributes to another tag from your component. Below I show an out of the box way to cascade the attributes from your wrapper component to a tag, in this case a button.

Example

Checkout a live Demo here EventHorizon.Blazor.UX.

You can also checkout the source of the whole site in the canhorn/EventHorizon.Blazor.UX Github repository.

Button.razor
A cascaded attributes example component. Show how you can expand on the class with your own and any that are also passed in.

<button class="my-awesome-button @@class" @attributes="Attributes">@ChildContent</button>

@code {
    [Parameter(CaptureUnmatchedValues = true)]
    public IDictionary<string, object> Attributes { get; set; }
    [Parameter]
    public string @class { get; set; }
    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

Example Usage of Button

<Button class="--font-size-huge" disabled>Huge Disabled Button</Button>

Generated HTML

<button class="my-awesome-button --font-size-huge" disabled>Huge Disabled Button</Button>


Categories: blog blazor

Tags: .NET Core C#


Cody Merritt Anhorn
Email: cody.anhorn@hotmail.com