Blazor Custom Checkbox Component

Hello coder! In this blog post, I’ve shared a method for creating your own custom Blazor Component for a Checkbox that you can reuse every time. The source code is also provided below.

Step 1:

First, create a Razor page in your Blazor project, and name it Checkbox.razor. Then, paste the following code:


    <input 
        type="checkbox" 
        id="@Id"
        checked="@Value"
        style="accent-color: @Color; width: @Size; height: @Size; @Styles"
        @onchange="OnValueChanged"
        readonly="@Readonly"
        disabled="@Disabled"/>
        
    <label for="@Id">@Label</label>

Step 2:

Create a partial class, naming it Checkbox.razor.cs, and paste the following code:


    using Microsoft.AspNetCore.Components;

    namespace BlazorComponent.Checkbox;

    public partial class Checkbox : ComponentBase
    {
        [Parameter] public bool Value { get; set; }
        [Parameter] public EventCallback<bool> ValueChanged { get; set; }
        [Parameter] public string? Id { get; set; }
        [Parameter] public string? CssClass { get; set; }
        [Parameter] public string? Styles { get; set; }
        [Parameter] public string? Label { get; set; }
        [Parameter] public bool Disabled { get; set; }
        [Parameter] public bool Readonly { get; set; }
        [Parameter] public string? Color { get; set; } = "#007bff";
        [Parameter] public string? Size { get; set; } = "1rem";
    
        protected override void OnInitialized()
        {
            if (string.IsNullOrWhiteSpace(Id))
            {
                Id = Guid.NewGuid().ToString();
            }
        }
        
        private async Task OnValueChanged(ChangeEventArgs e)
        {
            if (e.Value is bool value)
            {
                await ValueChanged.InvokeAsync(value)
                    .ConfigureAwait(false);
            }
        }
    }

Step 3:

Now, your custom checkbox component is ready to use. You can use the checkbox component as shown in the example below. Here, I’ve created a Razor page named Home.razor and pasted the following code:


    @page "/"

    <PageTitle>Home</PageTitle>

    <h1>Hello, world!</h1>
    <br>
    Welcome to your new app.

    <p>Value: @CheckedValue</p>
    <Checkbox @bind-Value="CheckedValue" Label="Red" Color="red"/>
    <Checkbox @bind-Value="CheckedValue" Label="Size" Color="blue" Size="60px"/>
    <Checkbox @bind-Value="CheckedValue" Label="Checked"/>
    <Checkbox @bind-Value="CheckedValue" Label="Disable" Disabled="true"/>
    <Checkbox @bind-Value="CheckedValue" Label="Readonly" Readonly="true"/>

    @code {
        public bool CheckedValue { get; set; }
    }

Happy Coding!!