Using Blazor components within React

One of the many cool things with Blazor is that we can actually use a Blazor component within a React application…

  • Create React app using
    yarn create react-app my-app-js
    

    In this example, we’ll use JS instead of Typescript, but I’ll show how to use Typescript later

  • Create a Blazor Web Assembly (or Server)
    dotnet new blazorwasm-empty -o BlazorComponents
    
  • Within the Blazor project, add a Blazor component, here’s a simple starter
    <h3>Welcome to My Component</h3>
    
    <button @onclick="UpdateCounter">OK</button>
    
    <div>@_counter</div>
    
    @code {
        int _counter = 0;
    
        private void UpdateCounter()
        {
            _counter++;
        }
    }
    
  • Add the Nuget package Microsoft.AspNetCore.Components.CustomElements
  • Within the Program.cs add
    builder.RootComponents.RegisterAsCustomElement<MyComponent>("my-component");
    

    The my-component is the name that gets used within the React app.

  • To test, simple add the component to you Blazor project’s Index.razor and then run the project
  • When you’re happy, run
    dotnet publish
    
  • We now need to copy the _content folder from ${project}\bin\Release\net9.0\publish\wwwroot to the public folder of the React app
  • In the index.html file within the public folder of the React application add the following before the </body> tag
    <script src="_framework/blazor.webassembly.js"></script>
    
  • Finally add our component (using the name we gave it earlier) to our React code, so for example my App.tsx looks like this
    <div className="App">
      <my-component></my-component>
    </div>
    

Now if we created our React application using Typescript, which is my usual way of doing this, using

yarn create react-app my-app-ts --template typescript

and if you follow all the instruction for the React side of things from above, you’ll find that there’s an error message displayed because <my-component> as it’s not an instrinsic JSX type, so the simplest way to handle this is to disable the error using ts-ignore, i.e.

<div className="App">
  {/* @ts-ignore */}
  <my-component></my-component>
</div>