Sometimes, you want to prevent an event from executing its default action. For instance, you may want to prevent a click on an anchor from navigating to the URL set in the href attribute, and instead handle the event in a custom way.
In JavaScript, the event.preventDefault() method tells the browser not to execute the default action. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation immediately.
In Blazor, you cannot directly use event.preventDefault(). Additionally, this method must be called synchronously, which is not possible in Blazor Server, since it processes events asynchronously by sending data to the server over the SignalR connection and waiting for a response. The solution is to use @event_name:preventDefault="true", which allows Blazor to call preventDefault before invoking the event handler.
Razor
<div @onclick="OnDivClick">
<a href="https://www.meziantou.net"
@onclick="OnAnchorClick"
@onclick:preventDefault="true" 👈 Prevent the navigation to the url but still executes OnAnchorClick
@onclick:stopPropagation="true"> 👈 Stop the propagation of the event (bubbling), so div.onclick is never called
Sample
</a>
</div>
@code {
void OnAnchorClick() => Console.WriteLine("Anchor click");
void OnDivClick() => Console.WriteLine("Div click"); // Won't be triggered if stopPropagation is set to true
}
You can also configure the value dynamically using a variable:
Razor
<a href="https://www.meziantou.net"
@onclick="OnClick"
@onclick:preventDefault="preventDefault">
Sample
</a>
@code {
bool preventDefault = false;
}
#Additional resources
Do you have a question or a suggestion about this post? Contact me!