Search code examples
blazorblazor-webassembly

Blazor WASM pass through multiple attributes (Equivalent to React {...props})


I'm making a variant of a component in Blazor WASM, see example below. But since this is a variant I want to pass through the original attributes without redefining everything again in the variant component.

// VariantTextField.razor
<OriginalTextField Value1="@Value1" Value2="@Value2">...<OriginalTextField/>

@code {
    [Parameter]
    public string Value1 { get; set; }

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

For example in React you can pass props through by doing this:

function ComponentVariant(props) {
  let value1 = "..."
  return <OriginalComponent value1=value1 {...props}>...</OriginalComponent>;
                                             ^^^^^
}

Is there an Blazor WASM equivalent of this?


Solution

  • In Blazor this is referred to as arbitrary parameters. And it will add all the unmatched attributes to the corresponding element. And it will be helpful if you have many attributes that are not necessarily needed to be predefined.

    So you will define a component parameter of type IDictionary<string, object>? and add [parameter attribute. But this time you will add CaptureUnmatchedValues and set it to true.

    Here is a working code example

    Component view:

    <div @attributes="AdditionalAttributes" extra="5" />
    
    @code {
        [Parameter(CaptureUnmatchedValues = true)]
        public IDictionary<string, object>? AdditionalAttributes { get; set; }
    }
    

    Parent view:

    <AttributeOrderChild1 extra="10" />
    

    Also, note that the example shows the priority which means that if the element has an existing attribute it won't be replaced/changed. Which is in our case the extra attribute value is 5.

    Microsoft docs to arbitrary attributes: Arbitrary Parameters