Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render react component inside Blazor page

Is it possible to render a react component inside a Blazor page? I tried adding script tags to the Blazor page, but Blazor does not allow adding script tags.

Thanks for the answer.

like image 337
Kristof Avatar asked Mar 30 '26 20:03

Kristof


1 Answers

Is it possible to render a react component inside a Blazor page?

Yes, it's possible. React is a javascript library and the same way you can add jquery to your blazor app, you can also add React to it, but it have some drawbacks.

I tried adding script tags to the Blazor page, but Blazor does not allow adding script tags.

Indeed, you can't add script tag in a .razor file and the place you should add is in the _Host.cshtml file

Now you may ask, how to add React to a Blazor app? Well.. it's a little complicated.

What you need to do is configure a webpack to generate all files from React and put then in wwwroot and reference all the scripts and links in the _Host.cshtml file.

And then you will need to attach to window a function that will render you react component, something like

// index.js from react
window.renderReactApp = function() {
    ReactDOM.render(<App />, document.getElementById("react-div"))
}

Drawbacks of adding React into a blazor app

1. Communicating between React and Blazor.

If you need to pass data (state) between React and Blazor, it will be a big struggle, you will need to create some sort of Flux pattern that will be the bridge between both. This takes time to do and using it can be confusing.

2. Too much effort for something you might be able to do with Blazor

If you are already using Blazor and want to add React, you need to have really strong reasons to do that. Otherwise, you will wast too much time on something that you could have done with less effort in Blazor

Good reasons to add React to Blazor

There is a lot of js libraries that probably won't be able to be created with Blazor, or if someone do it, probably will be just a wrapper of the js and...

So far, Blazor doesn't give any way for you to do things that webpack can do, so in some cases where you have a lot of javascript or css, you will want to configure a webpack to minify / do what you need with those files. In this case, if you are already configuring the webpack for that, adding react to it, will be no problem.

One example of this is MatBlazor. They use a lot of js and css from material design web components, so they use webpack to bundle everything up. They don't use React, but it's an example of how to use webpack in blazor (something you will need to do to have React in your blazor app)

like image 136
Vencovsky Avatar answered Apr 02 '26 04:04

Vencovsky