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.