Sharing Data between Blazor and JavaScript ( JS interop )
Tags: blazor, csharp, dotnet, javascript
Published: 2023-06-03 13:45:16

**

## 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();
    }
```

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


##  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; }
}
```



##  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));
        }
    }
}
```


```
function myJavaScriptFunctionWithCallback(dotnetReference) {
    const employee = {
        name: "Amine Nafkha",
        age: "2000-08-02"
    };
    const employeeJson = JSON.stringify(employee);
dotnetReference.invokeMethodAsync("ReceiveEmployeeFromJavaScript", employeeJson);
}
```

-  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)
    };
}
```


- 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");
    }
}
```

```
Implementing the changeButtonColor JavaScript Function: 
function changeButtonColor() {
    const button = document.querySelector('button');
    button.style.backgroundColor = 'red';
}

```

-  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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zieoh3zwln89qle3pkkn.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r2bpcv8qjgoy96t77lgm.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cras3lqbw8wscmgqxk4i.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4mf6k6dvvnv96ku41ui8.png)

View : 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qg2nkm8k9l6fwk9fbive.png)