Can't apply plain HTML class to a Blazor component

Viewed 768

I've tried to use this code in my .NET 5 Blazor project, in .razor file:

<SignedLabel class="some-css-class" Price=123 Currency=Currency.Usd />

where SignedLabel - is a Blazor component and Price, Currency is the component's input parameters. I expect Blazor to treat the class word as an html property and apply the plain HTML class to this component so that I can style this component later on. But Blazor actually treats it as another input parameter for component and crashes whole app rendering with error:

Object of type 'SignedLabel' does not have a property matching the name 'class'

So the questions is

  • Is it possible to use the class property in a such way?
  • If yes, how should I do this?

PS: project settings:

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>net5.0</TargetFramework>
        <Nullable>enable</Nullable>
        <LangVersion>9</LangVersion>
    </PropertyGroup>
    ...
</Project >
2 Answers

You cannot apply a class to a Component. You can use splatting to capture attributes placed on a Component to pass as parameter to one of the components elements.

SomeComponent.razor

<div @attributes="@CapturedAttributes">
    Hello
</div>
@code {
    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string,object> CapturedAttributes { get; set; }
}

##Usage

<SomeComponent id="fred" class="some-css-class" style="width:100vh" />

Will render:

<div id="fred" class="some-css-class" style="width:100vh" >
    Hello
</div>

Docs

You just have to create a Parameter in your component. For example, this works fine. In a Tree component, TopDivClass parameter has been added an used.

In the markup of the component:

<div class="@TopDivClass">

In the code behind of the component:

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

In the markup using the component:

<Components.Tree TopDivClass="TreeView" />

The result in the HTML is

<div class="TreeView" ...
Related