Getting started guide: https://reactjs.net/getting-started/aspnet.html
-
Install
React.Web.Mvc4
from NuGetThe file:
App_Start\ReactConfig.cs
will be created. -
Install
JavaScriptEngineSwitcher.V8
,JavaScriptEngineSwitcher.V8.Native.win-x64
andJavaScriptEngineSwitcher.V8.Native.win-x86
from NuGetNote: The official guide doesn't mention x86 but I could not make it work without it, perhaps you need to install a C++ redistributable (it's mentioned when installing the x64 package)
-
Change
ReactConfig.cs
to include:ReactSiteConfiguration.Configuration .SetLoadReact(false) // This makes it so that ReactJS.net uses the bundles version of React which I determined was required to make hooks etc work (https://github.com/reactjs/React.NET/issues/718) .SetLoadBabel(false) .AddScriptWithoutTransform("~/Scripts/bundle.server.js"); JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName; JsEngineSwitcher.Current.EngineFactories.AddV8();
-
In a view add:
@Html.React("HelloWorld", new { message = "Hello from C#!" })
-
To enable client side interactions: In the view that contains the
<html>
etc tags (for example_Layout.cshtml
) add the following-
In the
<head>
add:<script src="@Url.Content("~/Scripts/bundle.server.js")"></script>
-
Just before
</body>
(end of document) add:
@Html.ReactInitJavaScript() // Note: No need for the <scripts> tags since we include React, ReactDom etc in the bundle
-
- Install parcel globally
npm install -g parcel-bundler
- Create a file called
server.ts
. It should add any component you want to use in MVC to theglobal
object. Sampleserver.ts
:
import React from "react";
import ReactDOM from "react-dom";
import ReactDOMServer from "react-dom/server";
import { HelloWorld } from "./HelloWorld";
// Needed when we want to bundle React ourselves, also make sure to use SetLoadReact(false) in the ReactConfig.cs file
(global as any).React = React;
(global as any).ReactDOM = ReactDOM;
(global as any).ReactDOMServer = ReactDOMServer;
// Components to expose
(global as any).HelloWorld = HelloWorld;
-
Now create a bundle using parcel:
parcel build src/server.ts --out-file bundle.server.js
Tip: Add this to your
package.json
scripts:"bl": "rm -rf dist && parcel build src/server.ts --out-file bundle.server.js"
.Now you can simply write
npm run bl
(build library) -
Copy
dist/bundle.server.js
to theScripts
folder in MVC project.
Run the MVC project, hopefully everything is working :)