How to render conditional elements in Blazor like in React JSX?
For example in React
:
export const LoginPage: FC = () => {
// useState's
// useEffect's
return <div>{!loadingState ? usernameState : <Spin />}</div>; // <-- Goal
};
And I've tried in Blazor:
<div>
You logged in AS:
@if (_loading)
{
<Spin/>
}
else
{
@_userName
}
</div>
is there any way how to write this in one line?
CodePudding user response:
<div> You logged in AS: @if(_loading){ <Spin/> } else { @_userName } </div>
Amazing, right?
If you specifically want to use the ternary operator, then I'm not sure, I'd have to think on it for a bit.
CodePudding user response:
To answer your question:
How to render conditional elements in Blazor like in React JSX?
You can, but there are other ways to solve the example you show. Showing some form of visual control for loading is so common you can build a component control.
Here's a bare bones example:
LoadingControl.razor
@*@if (this.IsLoaded)
{
@this.ChildContent
}
else
{
<div class="loader"></div>
}*@
@_content
@code {
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public bool IsLoaded { get; set; }
private RenderFragment _loader => builder => builder.AddMarkupContent(0, $"<div class='loader'></div>");
private RenderFragment _content => this.IsLoaded ? ChildContent : _loader;
}
I've shown two ways you can render the content.
You then use it like this:
<div>
You logged in AS:
<LoadingControl IsLoaded="!_isLoading">
@_userName
</LoadingControl>
</div>