How to use event.PreventDefault in Blazor

  • Gérald Barré

Sometimes, you'll come across a situation where you want to prevent an event from doing what it does by default. For instance, you may want to prevent the click on an anchor to navigate to the url set in the href attribute. Instead, you want to handle the event in a custom manner and suppress the default behavior.

In JavaScript, the event.preventDefault() method tells the browser to not 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 at once.

In Blazor, you cannot directly use event.preventDefault(). Plus this method must be called synchronously which is not possible in Blazor Server. Indeed, Blazor Server processes event asynchronously as it needs to send the data to the server using the SignalR connection and wait for the response. So, the solution is to use @event_name:preventDefault="true", so Blazor can call the preventDefault method before calling the event handler.

<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:

<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!

Follow me:
Enjoy this blog?Buy Me A Coffee