Blazor Custom Button Component

Hello guys! In this blog post I have shared you the way of creating Blazor custom button component which you can reuse in your entire application. I also have shared source code below.

Step-1

First of all create a razor page on your project, let’s say Button.razor and paste the below code.


    <button
        class="btn @CssClass"
        id="@Id"
        style="@Styles"
        type="@Type.ToString()"
        disabled="@Disabled"
        @onclick="async() => await OnClick.InvokeAsync()">
        @ChildContent
    </button>

Step-2

Create a partial class for above razor page, let’s say Button.razor.cs and paste the below code.


    using Microsoft.AspNetCore.Components;

    namespace BlazorComponent.Button;

    public partial class Button : ComponentBase
    {
        [Parameter] public string? Id { get; set; }
        [Parameter] public RenderFragment? ChildContent { get; set; }
        [Parameter] public ButtonType Type { get; set; } = ButtonType.Button;
        [Parameter] public string? CssClass { get; set; } = "btn-primary";
        [Parameter] public string? Styles { get; set; }
        [Parameter] public bool Disabled { get; set; }
        [Parameter] public EventCallback OnClick { get; set; }

        protected override void OnInitialized()
        {
            if (string.IsNullOrWhiteSpace(Id))
            {
                Id = Guid.NewGuid().ToString();
            }
        }
    }

Step-3

Create a Enum for Button Type, let’s say ButtonType.cs and paste the below code.


    namespace BlazorComponent.Button;

    public enum ButtonType
    {
        Button,
        Submit,
        Reset
    }

Step-4

Our custom blazor button component is ready, just use it. I have shared the source code of using it below. Either use this code or take the references from below.


    @page "/"

    <PageTitle>Home</PageTitle>

    <h1>Hello, world!</h1>
    <br>
    <p>Counter: @Counter</p>
    <br>
    <Button OnClick="IncreaseCount">
        Increase Count
    </Button>

    <Button CssClass="btn-danger" OnClick="DecreaseCount">
        Decrease Count
    </Button>

    @code
    {
        private int Counter { get; set; }

        private void IncreaseCount()
        {
            Counter++;
        }
        
        private void DecreaseCount()
        {
            Counter--;
        }
    }

Happy Coding!!!