DotNetT2 Light_1200x303

With .NET 6 just around the corner, Microsoft has released its final pre-release versions of the framework (RC1 and RC2). Let’s see what they bring.

This close to RTM, the RC releases are primarily for catching last-minute bugs and performance tweaking, but in this case we also got a few new Blazor features that are worth flagging up.

Here are the highlights:

Collocate JavaScript With Your Components

If you’ve ever spent more than a few minutes hunting through code, desperately trying to locate that one line you need to change, you know the value of keeping related logic together.

From RC1, you can put the JavaScript for your component right next to the component itself, using the naming convention <Component>.razor.js.

For example, if your feature lives in Pages/Panel.razor, you could create a JavaScript file at Pages/Panel.razor.js.

Pages/Panel.razor.js

export function error(){
    alert('oops, an error');
}

Then reference it in your component:

Panel.razor

var js = await JS.InvokeAsync<IJSObjectReference>("import", "./Pages/Panel.razor.js");
await module.InvokeVoidAsync("error");

With this and the existing CSS isolation support, you can now feasibly keep all of your component’s assets together in one place:

  • Pages/Panel.razor
  • Pages/Panel.razor.js
  • Pages/Panel.razor.css

Manipulate the Query String

Preview 7 added the ability to populate component parameters from the query string.

RC1 adds the ability to go the other way—to easily update the query string from your Blazor components.

var newUri = NavigationManager.GetUriWithQueryParameter("searchTerm", "Blazor");
NavigationManager.NavigateTo(newUri);

The first line creates a new Uri with searchTerm=Blazor in the query string (added if it wasn’t there before, updated if it was).

The second line then navigates to the new Uri (including that query string).

GetUriWithQueryParameters makes it possible to update several parameters at once (by passing a dictionary of parameter values).

var newUri = NavigationManager.GetUriWithQueryParameters(new Dictionary<string, object?>
{
    ["searchTerm"] = "Blazor",
    ["pageSize"] = 20,
    ["page"] = 2
});
NavigationManager.NavigateTo(newUri);

PageX and PageY Are Now Available in MouseEventArgs

I’m guessing, if you ever tried to use MouseEventArgs in Blazor, you noticed the omission of the PageX and PageY properties.

Well it seems they’ve now been added (in RC1).

Render Blazor Components From Your JavaScript Code

RC1 brings the ability to render Blazor components from JavaScript.

This could be useful if you have an existing JavaScript app and need to gradually migrate it across to Blazor.

You can register any component “for JavaScript,” give it an identifier, then use that identifier to render the component from JavaScript.

Here’s an example using Blazor WebAssembly.

builder.RootComponents.RegisterForJavaScript<Greeting>(identifier: "my-greeting");

Now your Panel component will be available to render from JavaScript. Here’s a minimal example:

<!DOCTYPE html>
<html>

<body>

    <button onclick="addGreeting()">Greet Me</button>

    <script>
        async function addGreeting() {
            let targetElement = document.getElementById('container');
            await Blazor.rootComponents.add(targetElement, 'my-greeting', {});      
        }
    </script>
 
    <div id="container">
    </div>

    <script src="_framework/blazor.webassembly.js"></script>

</body>

</html>

If you need to pass parameters to your component, you can do that too:

await Blazor.rootComponents.add(targetElement, 'my-greeting', { name: 'Alice' });

One caveat to note: There doesn’t seem to be much documentation about this feature yet. It seems likely that will change once .NET 6 is officially released and real-world examples start to emerge.

Native Dependencies Now Supported in Blazor WebAssembly Apps

As you probably know, Blazor Wasm runs on WebAssembly.

WebAssembly itself is an open standard that you can target from a number of languages, including C, C++ and Rust.

Up until now, if you had existing native code (which runs on WebAssembly), there was no way to interact with it from Blazor.

RC1 fixes this, meaning you can now use native dependencies with Blazor (Wasm).

As Dan Roth notes in the official ASP.NET blog release notes, this means you can interact with C/C++ code, or code compiled to object files (.o), archive files (.a), bitcode (.bc) or standalone WebAssembly modules (.wasm).

Furthermore, native dependencies for use on WebAssembly can now be distributed via NuGet packages.

This opens the door for Blazor libraries to interact with existing WebAssembly dependencies (and for those libraries to be distributed via NuGet).

A Hint at Closer Integration With Other SPA Frameworks

Finally, we also got news of potential closer integration between Blazor and other web apps.

Experimental support was announced for building custom HTML elements with Blazor.

In practice this means you could create a Blazor component, say a Panel, then register it as a custom element.

builder.RootComponents.RegisterAsCustomElement<Panel>("panel");

From there, you could then use that panel component in another SPA framework (like Angular or React).

<panel></panel>

Check out the Blazor Custom Elements sample project for more details and a concrete example of how to do this and make it work with React and/or Angular.

It was also announced that work is in progress to make it possible to generate JavaScript framework-specific components for your Blazor components. This is possible thanks to the new support for rendering Blazor components from JavaScript.

In principle, you could add attributes to your Blazor components:

@attribute [GenerateReact]   // Generate a React component

Register them as Root Components:

builder.RootComponents.RegisterForReact<MyComponent>();

Then use them as if they were any other component (in your React project in this example).

It’s worth noting this capability isn’t included with .NET 6 and seemingly falls into the “early/experimental” category for now. There’s example code to explore on GitHub that shows it in action.

.NET 6 Is Nearly Ready

When the official release notes start pointing to experimental, early examples of what’s coming after .NET 6, you know that .NET 6 itself is almost ready!

Aside from a few small tweaks to the new project templates and some performance and stability tweaks, that’s just about it for .NET 6 preview releases. (In case you missed it, this post covers Blazor updates worth noting prior to the release candidates.)

.NET 6 will launch as part of .NET Conf November 9-11.


Jon Hilton
About the Author

Jon Hilton

Jon spends his days building applications using Microsoft technologies (plus, whisper it quietly, a little bit of JavaScript) and his spare time helping developers level up their skills and knowledge via his blog, courses and books. He's especially passionate about enabling developers to build better web applications by mastering the tools available to them. Follow him on Twitter here.

Related Posts

Comments

Comments are disabled in preview mode.