How to render a component on button click in Blazor?
Asked Answered
T

1

6

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?

Trespass answered 10/9, 2020 at 23:52 Comment(0)
W
7

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...

Waffle answered 11/9, 2020 at 0:11 Comment(2)
Thank you, sir. One last request, can you please provide a simple example to demonstrate what you mean when you say we can also do it by using a string variable instead of a boolean one, cuz I don't understand why we would do that.Trespass
@AmirHosseinAhmadi I´m not sure if this is what @Waffle meant, but you could for example fill a string variable in a method you call when clicking on the button. In the method you check if it´s a single left click, single right click, double left etc. and fill your string variable accordingly (e. g. stringClicked = "leftsingle"). Then you can show components by evaluating the value of a string variable.Fuel

© 2022 - 2024 — McMap. All rights reserved.