What is the difference between OnClick and @onclick in blazor components

Viewed 616

I found out something curious and I am wondering if anyone knows the answer:

First of all this is not this question: Different method calls in Blazor That question refers to HTML elements. I am talking about Components.

So I have my own component named MyButton; and it has OnClick Parameter specified:

MyButton.razor

<button @onclick="OnClick">Do Something</button>

@code {
    [Parameter]
    public EventCallback<MouseEventArgs> OnClick { get; set; }
}

When I use MyButton I can use either the name exactly, i.e.

<MyButton OnClick="SomeMethod" />

But this is also working:

<MyButton @onclick="SomeMethod" />

When I remove the whole @code block from the MyButton.razor they both give me the exact same error message:

<Mybutton OnClick="MyMethod" />

Object of type 'MyButton' does not have a property matching the name 'OnClick'.

<Mybutton @onclick="MyMethod" />

Object of type 'MyButton' does not have a property matching the name 'onclick'.

The only difference is in the caps; "OnClick" vs "onclick"... that is logical. So it seems @onclick is the same as OnClick... but are they?

Is this simply an overload of some sorts?

2 Answers

@onclick is the native HTML click event and OnClick is the event parameter you explicitly expose in your MyButton component.

So in this case you should use

<MyButton OnClick="SomeMethod" />

I tried to reproduce the usage with @onclick but it didn't work in my case.

For science, you could try to add a text <p>Like this</p> to your MyButton component and see if the @onclick event still works and if it only fires if you click the button or also if you click the text.

Also, see Microsoft Docs for detailed information.

Do you use MudBlazor ? Because I think OnClick is part of the MudBlazor Button API and @onclick is part of the ASP.NET Core Blazor event handling features.

Related