Reader small image

You're reading from  Mastering Blazor WebAssembly

Product typeBook
Published inAug 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803235103
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Ahmad Mozaffar
Ahmad Mozaffar
author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar

Right arrow

Consuming JavaScript in Blazor

By this point, we have developed components to render data and capture the user’s input and written logic and navigate between pages, all purely with C#, and that’s the big promise of Blazor. But a little bit of JavaScript is kind of needed in some cases.

Throughout this chapter, we are going to discover those cases with some real-world examples, along with the IJSRuntime interface, which is a Blazor built-in service that allows communication between C# and JavaScript and vice versa.

This chapter will cover everything you need to know about JavaScript in Blazor apps:

  • When and why we use JavaScript in Blazor apps
  • Calling JavaScript from C# code
  • Calling C# from JavaScript code
  • Turning an existing JS package into a reusable Blazor component

Technical requirements

Despite the fact that this chapter focuses mainly on JavaScript, no prior knowledge of JavaScript is required to proceed, as we only use basic JavaScript code and make sure to follow it with explanations. The code used throughout this chapter is available from the book’s GitHub repository:

https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_06/ChapterContent

The final cleaned version of the code can be found at the following link:

https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_06/Final

When and why we use JavaScript in Blazor apps

The main selling point of Blazor is that it lets us build modern web applications using C# instead of JavaScript and that’s 100% true, but the presence of capabilities in the browser that have been built around JavaScript for many years makes the use of JavaScript mandatory in some cases.

Blazor already uses JavaScript behind the scenes in its engine, for example, to manipulate the Document Object Model (DOM), access some special features in the browser such as local storage, and even deal with files.

Because of the length of use of JavaScript in web development compared to Blazor, there are thousands of packages and tools that have been built using JavaScript over the years by corporates and open source contributors, including rich text editors, image croppers, and stuff like that. Having the ability to communicate with JavaScript from Blazor gives you the power to leverage those utilities directly out of the box instead of...

Calling JavaScript from C# code

Now that we have learned why we need JS and the possible ways to reference it, it’s time to get some JS code executed by our Blazor app. We will cover three different scenarios:

  • Calling a basic JS method
  • Calling a JS method synchronously
  • Calling a JS method that returns data

Calling a basic JS method

In the previous section, we created the site.js file that contains the showAlert function. In the following exercise, we will call that function from the NavBar component where we will add a new Login button on the top-right side of our app.

For now, this button will show an alert, but later we will use it for authentication purposes:

  1. In the Shared folder, open the NavBar component and add a button with its own div, so by default, the button will show on the right-hand side of the page:
    <nav class="navbar navbar-expand-lg navbar-light bg-light">        .....

Calling C# from JS

When building software, a different means of communication between C# and JavaScript is required: calling C# methods from within JS code.

A good example of this is when you are trying to embed a pre-built JS library in your application, such as an image cropper or a rich text editor. In some cases, you want your app to react to changes that happen in those packages, so whenever a certain event occurs inside them, you need to fire a method in your C# code, for example, showing the dimension of the new image that the user is cropping using that JS utility.

Another example is reacting to some window changes in your app, such as when the user is resizing the window of the browser and you need to change some behaviors in your app. Maybe you have a list of emails and when the user clicks on one, it renders the email on the right-hand side. But if the user resizes the screen to make it smaller, you need the list of emails to be shown on its own page and when one email...

Turning an existing JS package into a reusable Blazor component

JS is extremely rich in open source libraries that have been around for years and solve many scenarios. One important utility you will need in almost every app is a rich text editor. The normal text input we have in HTML only allows the user to type plain text, but with a rich text editor, the user can style their content and make it more organized and aesthetically pleasing.

In the app we are developing, we have built a form so the admin can submit a new book. In this form is a description field where the user can describe the book. In this section, we are going to leverage an open source JS library that will give us a Markdown editor that is both easy and beautiful to allow an admin writing a book description to style it and add titles, sections, and even menus.

The library is called SimpleMDE – Markdown Editor and is available on GitHub under the MIT license. You can find it at the following link: https...

Summary

With what we’ve covered in this chapter, you should be equipped with all the knowledge and experience you need to deal with anything JS related in your application, be it taking advantage of some built-in JS capabilities or using pre-built packages in your app with ease.

Throughout this chapter, we have learned why and when to use JavaScript in our Blazor WebAssembly application. We discovered the possible ways to implement interaction between the two languages in both directions. To put everything together and show you how you can leverage JavaScript to its full potential in your app, we ended up importing an open source library, wrapping it, and making it Blazor-ready so we can use it just like any other Blazor component.

By completing this chapter, you should now be able to do the following:

  • Identify the purpose of JS in Blazor
  • Detect when it’s necessary to use some JS in your apps
  • Call JS methods from your .NET code and vice versa
  • ...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Blazor WebAssembly
Published in: Aug 2023Publisher: PacktISBN-13: 9781803235103
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar