5

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?

baltermia
  • 1,151
  • 1
  • 11
  • 26
Arad Alvand
  • 8,607
  • 10
  • 51
  • 71

1 Answers1

5

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

Arad Alvand
  • 8,607
  • 10
  • 51
  • 71
enet
  • 41,195
  • 5
  • 76
  • 113
  • 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. – Arad Alvand Sep 11 '20 at 00:14
  • @AmirHosseinAhmadi I´m not sure if this is what @enet 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. – devbf Sep 11 '20 at 12:24