Search code examples
c#cssasp.net-corerazorblazor

How can I randomly add CSS attributes to Blazor component from parent layer as Vue did?


Since I want to design some reusable Blazor components, I hope they could have a feature like this:

Suppose I have a custom component "MyComponent", I could add any CSS attribute to it when I am using it:

<MyComponent Class="custom-css1 custom-css2">
    some child content...
</MyComponent>

While in MyComponent, I usually fix some common CSS attributes to the top wapper just like this:

<div class="fixed-css1 fixed-css2">
    some child content...
</div>

That means I have to combine two parts of the CSS attributes together to make the final HTML like:

<div class="fixed-css1 fixed-css2 custom-css1 custom-css2">
    some child content...
</div>

So I guess I should have this patern:

<div class="@Classes">
    some child content...
</div>

@functions
{

    [Parameter]
    private string Class { get; set; } = "";

    private string fixedClass = "fixed-css1 fixed-css2";

    private string Classes
    {
        get
        {
            return $"{fixedClass} {Class}";
        }
    }
}

To reduce redundant code, I could make a base class that have a protected Class property and every component inherent from it, but I still can't avoid writing the same combine code in each one. I hope there is some solution to add those custom CSS directly in my base class, I guess I could achieve this by override BuildRenderTree method from ComponentBase clss:

protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            base.BuildRenderTree(builder);
        }

But unfortunately, I have tried all my ways to build manually but have no idea to get it done. I don't know how to get elements of my HTML ("div" for example) and add additional CSS attributes to it.

All these are about doing a feature as Vue could easily do. In Vue code, we could certainly add any attribute to a component and pass them down to the first element in the component.

Could anybody help me complete this goal or give me some suggestion?


Solution

  • I think your approach is fine, it just needs a little abstraction around it to make it readable and easily managed across multiple components.

    That's why I created this simple helper function library. It's exactly what you are doing in your code, but offers an API for consistency.

    https://www.nuget.org/packages/BlazorComponentUtilities/