Ways to display a React app in ASP.NET Core MVC

Viewed 619

I have got an existing ASP.NET Core MVC website and am looking at putting a React app onto one of the server-side views (e.g. under Views/gallery.cshtml). No complex routes involved here as it's purely a single view for the React app. By the way, the React app is created via create-react-app (CRA).

Whenever I go to a particular route, say /gallery, I am seeing the React app, otherwise, it'd be just rendered from MVC server-side views as per normal.

I am not keen to make the whole MVC website a SPA app, and interested to know if there's any other potential solutions to achieve this.

2 Answers

Although using npm run build might work, but I ended up with webpack/babel approach as I think it gives me better control in terms of bundling and optimization. The key bits are as follows:

.babelrc

{
    "presets": [
      "@babel/preset-react"
    ],
    "plugins": [
    ]
}

webpack.config.js

const path = require("path");

module.exports = {
    entry: {
        index: "./src/index.js"
    },
    output: {
        path: path.resolve(__dirname, "../wwwroot/dist"),
        filename: "[name].js"
    },
    module: {
        rules: [
            {
                use: {
                    loader: "babel-loader"
                },
                test: /\.js$/,
                exclude: /node_modules/
            },
            {
                use: ["style-loader", "css-loader"],
                test: /\.css$/i
            }
        ]
    }
}

So the React app is compiled and bundled by using webpack/babel, and then output to a nominated directory. I put it directly under the /wwwroot where it can be easily referenced in the MVC view.

Yes you can do that. after giving npm run build, copy the static folder in your mvc app root directory and give reference to those css and js on your view pages, it'll render your react app in to your mvc views.

Related