Search code examples
blazorblazor-server-sideblazor-webassemblyasp.net-blazor

How to render a component on button click in Blazor?


I'm new to SPA frameworks and Blazor so this will probably be an easy question to answer, although I couldn't find an answer anywhere else.

I want to show a component somewhere on the page as soon as the user clicks on a particular button. I have currently implemented it this way:

@page "/test"

<button type="button" @onclick="() => showSignUpComponent = true">
    Show Sign Up Window
</button>

@if (showSignUpComponent)
{
    <SignUp />
}

@code {
    bool showSignUpComponent;
} 

I was wondering if there is a better and cleaner way (i.e. the right way) to do something like this in Blazor, or is this the common and the "standard" way?


Solution

  • What you've done is fine, and I dare say, the standard way to do it!

    You can also do it in slightly different ways if you had different scenarios. For example, you could define a string variable instead of a boolean one and store some relevant information in it, etc.

    No need to dwell on it, however. What you've done is perfectly fine, and it shows that you do understand that when a UI event, such as 'click', is triggered the component is re-rendered, and there is no need to call the StateHasChanged...