How to embed Blazor in an existing react project?
At present, the official only provides two examples of angular and react, so this tutorial only uses the react tutorial
Ideas explained:
First of all, in the existing react project, we may have some components completed in Blazor, but we have no way to find out how to use blazor components lightweightly in react. Some people may use it iframe
to load Blazor projects, but I don’t like this very much. This way, so I asked a lot of big guys today, and some big guys said that they can use Blazor components directly in react, and found documents and examples (in fact, Microsoft has mentioned this in the Blazor document, but because it is in the document below There may not be many people in the example to read [Documentation Express] ( ASP.NET Core Razor Components | Microsoft Learn ))
first process
-
create
react
projectnpx create-react-app react-debug cd react-debug yarn or npm i
Add the following code to App.js
import React, {
useState } from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [nextCounterIndex, setNextCounterIndex] = useState(1);
const [blazorCounters, setBlazorCounters] = useState([]);
const addBlazorCounter = () => {
const index = nextCounterIndex;
setNextCounterIndex(index + 1);
setBlazorCounters(blazorCounters.concat([{
title: `Counter ${
index}`,
incrementAmount: index,
}]));
};
const removeBlazorCounter = () => {
setBlazorCounters(blazorCounters.slice(0, -1));
};
return (
<div className="App">
<header className="App-header">
<img src={
logo} className="App-logo" alt="logo" />
<p>
<button onClick={
addBlazorCounter}>Add Blazor counter</button>
<button onClick={
removeBlazorCounter}>Remove Blazor counter</button>
</p>
{
blazorCounters.map(counter =>
<div key={
counter.title}>
<my-blazor-counter title={
counter.title} increment-amount={
counter.incrementAmount}></my-blazor-counter> // 这里将是渲染razor组件的地方 `my-blazor-counter` 是在razor中定义的,会在下面讲到
</div>
)}
</header>
</div>
);
}
export default App;
Add the following reference to ispublic/index.html
generated by Microsoft.AspNetCore.Components.CustomElementsMicrosoft.AspNetCore.Components.CustomElements/BlazorCustomElements.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="_content/Microsoft.AspNetCore.Components.CustomElements/BlazorCustomElements.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
- create
WebAssembly
project
mkdir webassembly
cd webassembly
dotnet new blazorwasm-empty
WebAssembly
Folder and the empty project WebAssembly
created
needs to ensure that the project is 7.0 because currently only the preview of 6 and the official version of 7 are supported
for installationMicrosoft.AspNetCore.Components.CustomElements
<PackageReference="Microsoft.AspNetCore.Components.CustomElements" Version="7.0.2" />
Microsoft.AspNetCore.Components.CustomElements
is the main implementation that provides componentization
modified Program.cs
code
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// BlazorApp.Pages.Index可以修改成自己的渲染的razor组件
// my-blazor-counter就是上面提到的razor对应的标记 这样就可以在react通过my-blazor-counter去渲染BlazorApp.Pages.Index组件的内容了
builder.RootComponents.RegisterCustomElement<webassembly.Pages.Index>("my-blazor-counter");
builder.RootComponents.Add<HeadOutlet>("head::after");
await builder.Build().RunAsync();
webassembly.Pages.Index
Component related code
<h1>@Title</h1>
<p role="status">Current count: @currentCount</p>
<p>Increment amount: @IncrementAmount</p>
<button class="btn btn-primary" @οnclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
[Parameter] public string Title { get; set; } = "Blazor Counter";
[Parameter] public int? IncrementAmount { get; set; }
private void IncrementCount()
{
currentCount += IncrementAmount.GetValueOrDefault(1);
}
}
<style>
button {
font-weight: bold;
background-color: #7b31b8;
color: white;
border-radius: 4px;
padding: 4px 12px;
border: none;
}
button:hover {
background-color: #9654cc;
cursor: pointer;
}
button:active {
background-color: #b174e4;
}
</style>
How to check the running effect:
If you need to check the running effect, there are many ways, such as proxying Blazor and react together through code, so that you can preview while modifying,
But I do the simplest thing now,
first generate react build
yarn build
Copy all the files under the build directory to the next webassembly\wwwroot
, and overwriteindex.html
Then execute the dotnet program webassembly
to execute in the directory
dotnet watch
The browser will be opened, and the effect will be shown in the figure below, we can addAdd Blazor counter
The effect will be like this, can be clicked Click me
will condition Current count quantity click Remove Blazor counter
will delete the razor component
Well, the effect is almost like this,
Through this case, we can know that blazor can also be embedded in any existing project like react, and it is easy to use. If it is vue, it is not known whether it supports it. At present, the official only provides two implementations of angular and react, and supports webassembly and server, the current tutorial is the practice of WebAssembly , the server will be different,
end
Project address: 239573049/Use-blazor-in-react (github.com)
Official example: github address
Technical exchange group: 737776595
Token sharing;