Search code examples
htmlrazorblazor

Can't apply plain HTML class to a Blazor component


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 >

Solution

  • 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