8 Integrating with JavaScript libraries

 

This chapter covers

  • Wrapping JavaScript libraries to work with Blazor
  • Calling JavaScript functions from C#
  • Calling C# methods from JavaScript

While one of the major reasons for choosing Blazor is to write our frontend applications using C# to avoid JavaScript, there are some things that can still only be done using JavaScript. A great example of this is accessing the browser’s web storage APIs. It’s a common requirement to store data in either local storage or session storage, but both features can be accessed only via JavaScript code. Beyond just needing to use some JavaScript out of necessity, there are also many fantastic, feature-packed JavaScript libraries available that just aren’t available in C#. It makes sense to take advantage of these battle-tested libraries and not reinvent the wheel when we don’t have to.

The great news for us is that Blazor has some fantastic JavaScript interop APIs. Using these APIs, we can call into JavaScript and also have JavaScript call into our application. This allows us to wrap the interactions with JavaScript in either C# classes or components. Once this is done, the rest of our application just deals with either the C# class or the component and never needs to care about the underlying JavaScript call. If designed correctly, another benefit is that we can swap the JavaScript library out at any point for another JavaScript library or even a C# library if one becomes available.

8.1 Creating a JavaScript module and accessing it via a component

8.1.1 Testing out the RouteMap component

8.1.2 Calling JavaScript functions from C# and returning a response

8.2 Calling C# methods from JavaScript

8.3 Integrating the RouteMap component with the TrailForm

8.4 Displaying the RouteMap on the TrailDetails drawer

Summary