Applying one of the most basic good coding practices - DRY - Don't Repeat Yourself, here's a simple "button" component:
@if (Show)
{
@if (this.Disabled)
{
<button type="button" disabled @attributes=this.UserAttributes>@ChildContent</button>
}
else
{
<button type="button" @onclick="this.OnClick" @attributes=this.UserAttributes>@ChildContent</button>
}
}
@code {
[Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> UserAttributes { get; set; } = new Dictionary<string, object>();
[Parameter] public EventCallback<MouseEventArgs> OnClick { get; set; }
[Parameter, EditorRequired] public RenderFragment? ChildContent { get; set; }
[Parameter] public bool Disabled { get; set; }
[Parameter] public bool Show { get; set; } = true;
}
Which you can then use like this:
@page "/"
<h3>Test</h3>
<MyButton class="btn btn-dark" Disabled=this.disabled Show=this.show OnClick=this.OnClick>Click me</MyButton>
<MyButton class="btn btn-primary" OnClick=this.ChangeMe>ChangeDisableMe>Disable me</MyButton>
<MyButton class="btn btn-outline-info" OnClick=this.ShowMe>Show me</MyButton>
@code {
private bool disabled;
private bool show = true;
private void ChangeMeDisableMe(MouseEventArgs e)
{
=> disabled = !disabled;
}private void ShowMe(MouseEventArgs e)
=> show = !show;
private void OnClick(MouseEventArgs e)
{
// Do something
}
}
You can use this same pattern for your more complex stuff. Personally, I have a base component (directly implemented as a class) that implements the basics and then derived classes for the more complex stuff
[Polite] Please don't take this the wrong way, but I'm amazed how often DRY goes out the window when writing Razor code!