DEV Community

Cover image for Sharing Data between Blazor and JavaScript ( JS interop )
Nafkha-Med Amine
Nafkha-Med Amine

Posted on

Sharing Data between Blazor and JavaScript ( JS interop )

**

Introduction:

**
In the ever-evolving landscape of web development, developers are constantly seeking ways to leverage the strengths of different technologies and frameworks. One powerful combination that has emerged is the integration of Blazor, a framework for building web applications using C#, with JavaScript, the ubiquitous language of the web. This integration opens up a world of possibilities, allowing developers to seamlessly share data between Blazor components and JavaScript code.

Sharing data between Blazor and JavaScript is not just a mere technicality; it represents a bridge that connects the robust, type-safe world of C# with the extensive JavaScript ecosystem. It enables developers to harness the power of existing JavaScript libraries, access browser APIs, and collaborate with JavaScript-only components, all while enjoying the declarative programming model and familiarity of C#.

In this article, we will dive deep into the realm of data sharing between Blazor and JavaScript. We will explore the what, why, and how of sharing data.

**

Steps :

**

we will walk through a series of use cases that demonstrate the seamless sharing of data between Blazor and JavaScript :

1. Setting up the Project

To set up JavaScript interop in your Blazor project, you need to follow a few steps. First, create a folder named js (or any other name you prefer) inside the wwwroot folder. This folder will store your JavaScript interop files.

Inside the js folder, create individual JavaScript files for each JavaScript interop functionality you want to include. For example, you can have myInterop.js, otherInterop.js, etc. These files will contain the JavaScript functions and event handlers you want to interact with from your Blazor components.

In your Blazor component, use the @inject directive to inject the IJSRuntime dependency. This allows you to interact with JavaScript code from your Blazor component. For example, you can call JavaScript functions, handle JavaScript events, and pass data between JavaScript and Blazor.

To include the JavaScript interop files in your Blazor application, add a reference to the JavaScript files in the _Host file located in the Pages folder. Use the script tag and provide the relative path to the JavaScript file. This ensures that the JavaScript code is loaded when the application starts.

2. Defining the JsonSerializable Class :

Provide the code for the "JsonSerializable" class, which facilitates serialization and deserialization of objects. Emphasize its role in converting objects to JSON format and vice versa.

public interface IJsonSerializable
    {
        string ToJson();
    }
Enter fullscreen mode Exit fullscreen mode
public class JsonSerializable : IJsonSerializable
{
    public string ToJson()
    {
        return JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Creating the Employee Class :

Introduce the "Employee" class as an example data model that inherits from the "JsonSerializable" class. the class and its properties, such as "Name" and "Age," which will be used for data sharing.

public class Employee : JsonSerializable
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("age")]
    public int Age { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

4.Use Cases :

Here are the JavaScript interop cases with examples that you can include :

  • Handling JavaScript events in Blazor :
@inject IJSRuntime jsRuntime

<p>Received employee from JavaScript: <span>@employee.Name @employee.Age </span></p>

@code {

    [JSInvokable]
    public void ReceiveEmployeeFromJavaScript(string employeeJson)
    {
        var employee = JsonConvert.DeserializeObject<Employee>(employeeJson);

    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await jsRuntime.InvokeVoidAsync("myJavaScriptFunctionWithCallback", DotNetObjectReference.Create(this));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
function myJavaScriptFunctionWithCallback(dotnetReference) {
    const employee = {
        name: "Amine Nafkha",
        age: "2000-08-02"
    };
    const employeeJson = JSON.stringify(employee);
dotnetReference.invokeMethodAsync("ReceiveEmployeeFromJavaScript", employeeJson);
}
Enter fullscreen mode Exit fullscreen mode
  • Calling JavaScript functions from Blazor
@inject IJSRuntime jsRuntime

<button @onclick="async () => await jsRuntime.InvokeVoidAsync("myJavaScriptFunction", employee.ToJson())">Call JavaScript Function</button>

@code {
    private Employee employee = new Employee
    {
        Name = "Amine Nafkha",
        Age = new DateTime(2000, 8, 2)
    };
}
Enter fullscreen mode Exit fullscreen mode
  • Manipulating the DOM from Blazor Defining the ChangeButtonColor Method:
@inject IJSRuntime jsRuntime

<button @onclick="() => ChangeButtonColor()">Change Button Color</button>


@code {
    private async Task ChangeButtonColor()
    {
        await jsRuntime.InvokeVoidAsync("changeButtonColor");
    }
}
Enter fullscreen mode Exit fullscreen mode
Implementing the changeButtonColor JavaScript Function: 
function changeButtonColor() {
    const button = document.querySelector('button');
    button.style.backgroundColor = 'red';
}

Enter fullscreen mode Exit fullscreen mode
  • Interop with third-party JavaScript libraries

Blazor's JavaScript Interop feature opens up a world of possibilities for integrating various third-party JavaScript libraries into your applications. One popular library is ApexCharts, which provides feature-rich and interactive charting capabilities. With Blazor's Interop, you can seamlessly utilize ApexCharts within your Blazor components to create stunning visualizations. Here's an example code snippet showcasing the integration of ApexCharts in Blazor:

Create a new JavaScript file, for example, chartInterop.js, in your project's wwwroot/js folder. This file will contain the JavaScript code for rendering the ApexCharts. :

Image description
Image description

Open the _Host file located in the Pages folder, and add the following line to import the JavaScript file:

Image description

In your Blazor component, inject the IJSRuntime service and invoke the JavaScript function :

Image description

View :

Image description

Top comments (2)

Collapse
 
artydev profile image
artydev

Great, thank you

Collapse
 
timexpeachtree profile image
Timex Peachtree

Great awesome code. Thank you for publishing.