Custom Blazor component with custom child components

Viewed 3635

I recently started using Blazor and find it a very promising technology.

I'm at the point of making custom nested Blazor components, but I don't seem to get it working the way I want.

The goal is to have a "Content" component which has a "ContentHeader" and a "ContentBody" property. However, the "ContentHeader" should be another custom component with a "Title" and "ActionBar" properties. The desired usage is as following:

<Content>
    <ContentHeader>        
        <Title>
            Title
        </Title>        
        <ActionBar>
            <button>Test button</button>
        </ActionBar>
    </ContentHeader>
    <ContentBody>
        Body
    </ContentBody>
</Content>

"Content" component:

<CascadingValue Value="this">
    <div class="content-container">
        @ContentHeader(Header)
        <div class="content-body">
            @ContentBody
        </div>
    </div>
</CascadingValue>

@code {
    [Parameter]
    public RenderFragment<ContentHeader> ContentHeader { get; set; }

    [Parameter]
    public RenderFragment ContentBody { get; set; }

    public ContentHeader Header { get; set; }

    public async Task SetContentHeader(ContentHeader contentHeader)
    {
        Header = contentHeader;
        await InvokeAsync(StateHasChanged);
    }
}

"ContentHeader" component:

<div class="content-header">
    <h3>@Title</h3>
    <div class="content-header-action-bar">
        @ActionBar
    </div>
</div>

@code {
    [CascadingParameter]
    public Content Content { get; set; }

    [Parameter]
    public RenderFragment Title { get; set; }

    [Parameter]
    public RenderFragment ActionBar { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await Content.SetContentHeader(this);
        await base.OnInitializedAsync();
    }
}

The actual rendered output I get is this:

<div class="content-container">
    <!--!-->
        Title
    <!--!-->        
    <!--!-->
    <button>Test button</button>
    <!--!-->
    <div class="content-body">
        <!--!-->
        Body
    </div>
</div>

It seems like the "ContentHeader" component its markup is completely ignored. The <h3></h3> tags around the Title of the "HeaderComponent" are missing and the button isn't placed inside <div class="content-header-action-bar"></div>

I also notices that OnInitializedAsync of "ContentHeader" isn't triggered.

What am I doing wrong? Am I even using the right approach?

Many thanks in advance.

Kind Regards

1 Answers

The way you are trying to do it is not right, unless you are rendering your @ActionBar your self, which I don't think you were trying to.

This is from my open source project Blazor Chat:

Source: https://github.com/DataJuggler/BlazorChat

Live Site: Not many users at once https://blazorchat.com

This is my Index page. ScreenType is an Enumeration variable.

@if (ScreenType == ScreenTypeEnum.Join)
{ 
    <Join Parent=this></Join>
}
else if (ScreenType == ScreenTypeEnum.Login)
{
    <Login Parent=this></Login>
}
else
{
    <Chat Parent=this></Chat>
    @if (TextHelper.Exists(Message))
    {  
        <div class="message">
            @Message
        </div>
    }
}  

With the Parent=this, the child components and parent components and pages can communicate via interfaces. I am not going to go into that here, but if anyone is curious here is a blog post I wrote on the subject about six months ago:

https://datajugglerblazor.blogspot.com/2020/01/how-to-use-interfaces-to-communicate.html

I can't post an entire project, but here are some relevant parts, that might help you better understand parent / child components.

This is an example in the project of a component, having multiple child components:

Chat.razor:

@if (HasUser)
{
    @if (Connected)
    {
        <div class="chatroom2">
            @if (ListHelper.HasOneOrMoreItems(Messages))
            {
                foreach (SubscriberMessage message in Messages)
                {
                    <SpeechBubble Message=message>
                    </SpeechBubble>
                }
            }
        </div>
        <div class="whoseonlist">            
            @if (ListHelper.HasOneOrMoreItems(Names))
            {  
                @foreach (SubscriberCallback callback in Names)
                {
                    <button class="listbutton" @onclick="(Action<EventArgs>) (args => 
SendPrivateMessageClicked(args, callback.Id))">@callback.Name</button><br />
                }
            }
            <textarea class="typedtext" @bind="MessageText"></textarea>
            <button class="greenbutton8" 
@onclick="BroadCastMessage">Broadcast</button>
            <div class="privatemessageinfo">
                Click a name to send<br />a private message.
            </div>
        </div> 
    }
    else
    { 
        <div id="ChatRoom" class="chatroom">
            <div class="moveup4">
                Enter Chat<br />
                <input type="text" @bind="SubscriberName" /><br />
                <button class="greenbutton6" 
@onclick="@RegisterWithServer">Connect</button>
            </div>
        </div>    
    }
}
else
{
    <div class="loginorjointochat">
    </div>
}

If you do want to render HTML, the speech bubble has a message property, and it sanitizes the HTML. So if a user types in, I found this cool site https://pixeldatabase.net (my site), the Sanitized code is rendered as a hyper link (I do a text replace and turn it into an anchor tag), but also if a message contains a bold tag, the text is rendered as Bold, or HTML line breaks work for breaking up lines, etc.

foreach (SubscriberMessage message in Messages)
{
    <SpeechBubble Message=message>
    </SpeechBubble>
}

This works thanks to this Nuget package: HtmlSanitizer

And the reference for it is Ganss.XSS, which took me a while to figure out.

Here is a class with an extension method if anyone wants it:

using Ganss.XSS;
using Microsoft.AspNetCore.Components;

namespace BlazorChat
{
    public static class MarkupStringExtensions
    {
        public static MarkupString Sanitize(this MarkupString markupString)
        {
            return new MarkupString(SanitizeInput(markupString.Value));
        }

        private static string SanitizeInput(string value)
        {
            var sanitizer = new HtmlSanitizer();
            return sanitizer.Sanitize(value);
        }
    }
}

Here is a screen shot of rendered HTML text:

enter image description here

Related