Search code examples
blazorblazor-server-side

Blazor: Conditionally display RenderFragment component


I've designed a simple blazor component which is a wrapper for a card. The usage looks like this:

<Card Title="Some title">
    <CardBody>My body content</CardBody>
    <CardFooter><a href="...">Go</a></CardFooter>
</Card>

It's pretty straightforward to use. However, in some cases, I do not wish to use the CardFooter component. But I cannot conditionally choose to render CardFooter. The If statement cannot be outside like this:

@if(myCondition){<CardFooter><a href="...">Go</a></CardFooter>};

It must be inside like this:

<CardFooter>@if(myCondition){...display something};</CardFooter>

The problem is I have to render an empty CardFooter regardless. I wish I could use the IF statement to decide not to render the footer at all. Is it possible?

Thanks!


Solution

  • If <CardBody> and <CardFooter> are subcomponents of <Card> then add a parameter on your <Card> component.

    [Parameter] public bool ShowFooter { get; set; }
    

    Then, from the host use:

    <Card ShowFooter=@myCondition>
    

    Then inside your <Card> component, use:

    @if (ShowFooter)
    {
        <CardFooter>Content</CardFooter>
    }