How to integrate ReactJS in existing ASP.net MVC app

React is a great front-end library where the concepts are easy to grasp such as state and components, but it can be confusing, a little bit difficult to integrate without the use of boilerplate like create-react-app.

According to the official page, React serves as a “V” in MVC. I’ve been trying to scratch my head for years before I got the concept and how can I integrate it gracefully in my existing ASP.net MVC app.

A lot (or some) of you may be wondering about how we can integrate ReactJS into ASP.net MVC app for the longest time. I actually wondered about that myself as well since my tech stack revolves around .net ecosystem until I learned how to make use and integrate it the hard way.

Like you, I digged deeper into the rabbit hole till I found the answer by learning the front-end ecosystems surrounding React, etc.

Having found the solution, let us answer how we can integrate ReactJS in our existing ASP.net MVC app:

Ways to integrate ReactJS in ASP.net MVC

As some of you might have know already, there are a couple of ways we can integrate ReactJS in our existing ASP.net MVC projects. Here they are:

Importing the React script

This is by far the easiest approach among the three, but you won’t be able to utilize JSX syntax with this method. You’re going to use plain javascript methods to construct your own React components.

So it’s up to you to use this method or not. You can find the cdn links here to get started with React right away.

Using ReactJS.net

ReactJS.net is a .net library that allows you to make use of JSX syntax on the fly by installing it via nuget package. You can find it here.

Using Webpack and Babel

Last but not the least is integrating through the use of webpack and babel.

This is by far is my favorite method of integrating the front-end library to our existing ASP.net MVC app as it’s flexible, customizable, and we can tune the performance of React at will through the use of webpack.

Personally, I prefer this method over the two. Here’s why:

  • Have better controls on the juicy stuffs of javascript ecosystem – Things like ES8, dynamically import ES modules, new React syntax definitions, etc. I feel like I’m missing a lot in javascript ecosystem without having to know how to make use of webpack. And since you can customize everything yourself, you can have the latest features of ECMAScript as you like at your fingertips.
  • Customizable scripts – Allows you to customize how webpack should compile/transpile React source code efficiently with less bloatware.
  • Better Separation of Concerns for React components and MVC – What I appreciate most in using webpack and babel is the fact that I have better controls on how can I separate React components from MVC structure of ASP.net. Although you might be able to achieve this using ReactJS.net as I haven’t used it.
  • Improve script performance – One of my favorite things about webpack is its ability to optimize and improve the performance of the script bundle. React just simply gets attached to the DOM once loaded, so you could imagine how expensive this operation is since it loads all components and scripts associated with that React DOM. And that’s where the script performance optimization of webpack comes into play.
  • Improve your knowledge in javascript ecosystem – This is by far the main reason why I learned webpack and babel down to my core is also because to strengthen my knowledge in javascript ecosystem. This allows me to grasp the front-end side of things and improve the loading speed.

We are going to use this method for the most part. If you have no knowledge in webpack and babel, don’t worry. We won’t delve deeper into these tools but just scratch the surface enough for you to understand the basics and integrate React into ASP.net MVC projects with less hassle.

What can I expect in this tutorial?

What you’ll expect in this tutorial is a straightforward, direct approach of integrating React using Webpack and Babel. What this tutorial doesn’t do is give you bunch of definition about what webpack and babel is.

If you’re looking for their definition and in-depth implementations, look elsewhere. If you don’t have any prior knowledge of these tools, don’t worry. I will make it as less complicated to implement as possible.

So, let’s get the hacking started!

Integrating ReactJS using Webpack and Babel

We are now going to delve deeper on implementing React using Webpack and Babel. Let’s get started!

Check your existing ASP.net MVC project

ASP.net MVC template

Check what version of MVC are you using. Is it 4? 5?

Either way, it doesn’t matter. What matters to us is the “Scripts” folder. If there’s nothing in the project, create one so that it follows the structure of our tutorial.

Initialize package.json file

We need to initialize the package.json file if we were to make use of webpack since we’re going to use npm to download and use the package later on.

To do that, go to command prompt and type this command:

npm init -y

This will initialize package.json file for you. And after typing that command you will see something like so:

Now you will have package.json in the project and you can now start installing npm packages.

Install npm packages

Now we need to download the webpack using npm commands since we now have package.json file. To do so, type this command:

npm install webpack webpack-cli --save-dev

We include --save-dev parameters to tell npm that this package file should be saved in package.json in any case other developers will download the repository for development use and install all packages in their local machine using npm install.

Now let’s also install react-related packages:

npm install react react-dom --save-dev

These packages allow you to use react components at your script.

Lastly, we need to install the following scripts related to babel:

npm install @babel/core @babel/preset-react babel-loader --save-dev

This allows us to make use of babel to transpile our react components. More into that later.

Creating root script for ReactDOM

We need to create a script for all your components to load in root element. So create a src folder under Scripts folder and create new script file named index.js under src folder then paste the following code:

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => <div>Hello world!</div>;

ReactDOM.render(<App />, document.getElementById("root"));

We are going to use this script later on when we setup our webpack config file.

Setting up webpack config file

Once all the npm packages we need were done installing, next is we need to setup webpack configuration file. Although, webpack claims zero configuration on our part, it’s still better to configure it ourselves to have better control over the script and its performance for bundling. To know more about webpack, go over here.

To start, create a folder named config and add webpack.config.js file into Scripts folder and paste this source code:

const path = require("path");

module.exports = {
    entry: {
        index: "./Scripts/src/index.js"
    },
    output: {
        path: path.resolve(__dirname, "../dist"),
        filename: "[name].js"
    },
    module: {
        rules: [
            {
                use: {
                    loader: "babel-loader"
                },
                test: /\.js$/,
                exclude: /node_modules/ //excludes node_modules folder from being transpiled by babel. We do this because it's a waste of resources to do so.
            }
        ]
    }
}

Let us explain the following details:

Entry – The starting point of your script. This is where you usually put all the starting scripts that initiate ReactDOM and its components to load (usually index.js). You can have multiple entries as you like.

Output – This is where you put the output files that was generated as a result of your script in entry point.

  • Path – this is the path that determines the output folder. In this parameter, we put “dist” as our folder where we put our output files for later use
  • Filename – This is the filename of your output. If you have two or more entry, you need to use a variable as its filename to reflect it from its entry point name. In this case, we used “[name]” as a variable for substitution. Learn about multiple entry points here.

Module – This is where you determine how the different types of modules will be treated. We will make use of “babel-loader” module to transpile React components in this part. Learn more about module here.

Setting up babel

Babel’s role in webpack ecosystem is to transpile various ECMAScript versions and React. It serves as a transpiler/compiler for webpack. Learn more about babel here.

Create .babelrc file in root folder and paste this:

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

What’s happening here is we are telling babel to use react presets so that we can transpile React. To know more on react presets in babel and you want it to configure further, look over here.

It’s that simple.

Building React scripts using Webpack

We are now ready to build react using webpack so we can make use of it in our View page.

To start building, run this in your command prompt:

webpack --config=Scripts/config/webpack.config.js

This will start creating a dist folder and build files which we will need for our View page.

Transferring webpack command to package.json

Instead of typing this whole command:

webpack --config=Scripts/config/webpack.config.js

We can go over and transfer this onto package.json file for ease of use.

Open your package.json file and paste this under scripts object:

"build": "webpack --config=Scripts/config/webpack.config.js"

This allows us to reuse the command without typing the whole command.

Now back to command prompt and type this:

npm run build

This does the same thing as our webpack command as we put it as shortcut in our package.json configuration file.

Importing the build file in View page

Since we can’t import React JSX directly in the view page, we still need the help of webpack and babel to do those stuffs for us.

So, after we run the command above, you should see the dist folder inside the Scripts folder on where we tell our webpack config to save the output files in Scripts/dist folder.

It should look like this in your project:

Include this folder in your project and let’s import index.js in our View page. Then paste this code inside your Home/Index.cshtml page:

<div id="root"></div>


@Scripts.Render("~/Scripts/dist/index.js")

Then your page will look something like this now:

Conclusion

We now have a basic gist of using React in existing ASP.net MVC projects and make use of the power of both webpack and babel in our projects. Let me know your thoughts or when you get into trouble in following the tutorial!

A Software Engineer who loves to code and write articles.

Leave a reply:

Your email address will not be published.

Site Footer