Implementing Micro Frontends using .NET Blazor WASM
Tags: dotnet, blazor, microfrontend, react
Published: 2021-12-11 15:47:57

## Preamble
Below is a question from StackOverflow emphasizing the need for this article.
{% stackoverflow 65842239 %}

## Table Of Contents
* [Disclaimer](#disclaimer)
* [To start with...](#start)
* [Now, the main stuff](#main)
* [Setting things up...](#setup)
* [Creating a friendly Folder Structure](#folder)
* [JavaScript Interop](#js)

## TL;DR

Here is a link to the github repository. Feel free to clone, download or fork and make PRs.
https://github.com/XanderSelorm/MicroFrontendsExample

## Disclaimer <a name="disclaimer"></a>

Kindly note that this tutorial is for educational purposes only and that this set up or architecture has not been tested in a production environment yet.

## To start with... <a name="start"></a>

Let's begin where every project begins! 

* Create a new Blazor Web Assembly app.
* Name the Project as `MicroFrontendsExample.Shell`.
Note that this particular project will serve as our app shell.
* Maintain the solution name as is: `MicroFrontendsExample`.
* For this project, we'll use .NET5.0 as the targeted version.

**Please note** that for this guide, I'll stick to using Visual Studio for the project set up.

![New Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a96ax0oidv1zpgckftg5.png)

With our container app/app shell ready, let's begin adding the individual micro frontends.

## Now, the main stuff <a name="main"></a>

Let's start with first adding micro frontends based on other JS frameworks. We'll start with **React.js** due its popularity. Also, we'll be making use of one major feature of Blazor - JavaScript Interoperability (JsInterOp).

To do this, let's add a new Class Library.

* Right click on the solution > Add > New project 
* Search for 'Razor Class library' and select it.

![Add New Razor Class Library](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/arp2zwh6lx1iad8jeebo.png)  
* Click 'Next'

On the next screen, 
* Enter the name of the Class Library (`ReactMicroFrontend` in our case) and click 'Next'
* Select .Net5.0 as the version
* Click on 'Create'

Voila! That was easy, right?

Now, onto the good stuff - Setting up the React Micro Frontend. Yay!🙏🏽

Since we're working with Blazor, it basically means that we won't be making use of any `HTML` - only `.razor`. 
I know you're wondering "so where will React's entry point be?" Hold your horses!😀 "do not be afraid", I've got you 😎.

We only need one Blazor component here which will call React's bundled file(s). Don't worry, you'll get what I mean along the line. 😉

## Setting things up... <a name="setup"></a>

Firstly, let's add the `ReactMicroFrontend` as a Project Reference to the main Blazor App. This will enable the container app or app shell recognize our class library as a part of itself (in layman's terms).

Do this by:
* Right-clicking on the main Blazor project (`MicroFrontendsExample.Shell`) 
* Select `Add > Project Reference`. 
* In the pop-up window, check the various projects/class libraries that are meant to be your micro frontend applications (`ReactMicroFrontend` in our case). 
* Click OK.

With that being done, let's go ahead and do some more set up.

## Creating a friendly Folder structure <a name="folder"></a>

Let's have a look at how our Class library looks like so far.

From the Solutions Explorer, this is what it looks like:
![React Micro Frontend](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jf1tk6hbu1ewyxdllczb.png)

Now that we've seen how it looks like, let's start with some modifications to make it react friendly.

Setting up a folder structure for your micro frontend is solely dependent on the preferences of the team involved (choice of architecture/principle).

Let's do some easy stuff! Deleting and creating a couple of files and folders. 

* Let's delete the `ExampleJsInterop.cs` file, and the `Component1.razor` file.
* In the `wwwroot` folder, let's delete the `background.png` and the `exampleJsInterop.js` files too.

With all that done, we'll create one new file - the entry-point file (`App.razor`) file.
* Right click on the `ReactMicroFrontend` > Add > New Item > Razor Component.
* Give your file a name at the bottom, and click 'Add'.

Using the same method, let's create a folder called `src`.
* Right click on the `ReactMicroFrontend` > Add > New Folder.
* Give your folder a name and click away.

Moving ahead...

* Within the `wwwroot` folder, create another folder called `dist`.

Let's throw some more light on the reasons for these massive overhaulings :D 

![Folder Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bpnfhurubxn8sxfc0x3k.png)
 
1. The `App.razor` file is the entry point of the React Application. It is through this file that the react application is loaded onto the blazor wasm framework.

2. The `_imports.razor` file contains any namespace we'd want available throughout the scope of the Class Library.

3. The ‘wwwroot’ folder contains a ‘dist’ folder where the bundled react app is placed after the react app is built with ‘npm run build’.

4. The ‘src’ folder is where the react application/codebase resides.

At this point, if you should run your app, you'll be greeted with the default boiler-plated pages from blazor:

![First App Run](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ityb6798v2b6yta3s25b.png)

The next and final thing to do for this part of the series is making sure that the JavaScript codes we'll be writing will be made available to our browser through what we call:

## JavaScript Interop <a name="js"></a>

In this topic, we'll have a look at how to configure the JavaScript interop in the `ReactMicroFrontend` to allow us build the JavaScript together with the C#. If you want to read more about JavaScript InterOp in Blazor, [check it out here](https://blazor-university.com/javascript-interop/).

* To begin, let's make some modification to our `App.razor` file. Add the following block of code:

```html
@page "/ReactMicroFrontend"

<div id="react-app"></div>
```
The above `<div>` with an `id` of `react-app` serves as the main entry point of our javascript code. In other words, it is in this `<div>` tag that our javascript code will be rendered.

* Secondly, lets add another file and name it `App.razor.cs`. This file will serve as a code-behind file where we'll keep all the JavaScript InterOp logics.
After creating the file, open it and add the following block of code and customize it as the need be:

```cs
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReactMicroFrontend
{
    public partial class App
    {
        [Inject]
        IJSRuntime Jsr { get; set; }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            //renderJs here is the name of our
            //javascript function which will render our React app
            await Jsr.InvokeVoidAsync("renderJs");
            await base.OnAfterRenderAsync(firstRender);

        }
    }
}

```

...and that, my friends, is a good start!

## Let's take a break here
In following parts of this series about Micro Frontends in .NET Blazor WASM, I'll delve deeper into the setting up of React.js in the new Class Library we created.

Stay Tuned! Cheers!!!