MVC is a design pattern used to decouple user interface(view), data(model), and application logic(controller). This pattern achieves separation of concern.
We can Integrate React JS with ASP.Net MVC Razor and Blazor Pages with help of Babel and Webpack.
Babel
- Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
- It transforms the syntax and set the missing pollyfills features to your environment.
Webpack
- Webpack is a static bundler for modern JavaScript applications, when webpack process your application.
- From V4.0, webpack doesn’t require configuration file to bundle the project.
CREATE NEW MVC PROJECT
- Open Visual Studio and Create a new Solution or Project.
- Select ASP.NET Core WebApp (MVC) and make sure that you are focused to select on C# language.
- Click Next.
- Give Project Name and Path to the Solution and Project. (Here am using test-react-mvc as project name)
- Click Next to create solution.
- Now your Project solution is getting ready.
INSTALLATION OF BABEL AND WEBPACK
- Stop the Solution and right click on the Project, Select Open in Terminal.
- Run the command npm init , for generating package.json to install node modules packages and dependencies
- Now, Package.json was created with details entered for package.json file.
- In terminal run the below command to install Babel and webpack.
npm install @babel/core @babel/preset-env @babel/preset-react babel-loader browser-sync-webpack-plugin webpack webpack-cli –save-dev
- Click show-all button to show the node_modules folder. Right click the node_modules folder and select Include in Project
INTEGERATION OF REACT
- Open Terminal and run the command npm install react react-dom –save
- Create View for Home Controller and named as Index.cshtml.
- Create div id as react-root
- Create components folder and add Index.js and App.js
- Create webpack.config.js in Project level and paste this code in that file.
module.exports = {
context: __dirname,
entry: "./App.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js",
},
watch: true,
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
}]
}
}
- Run command in Terminal, webpack –mode development .If the webpack not recognized install webpack globally and then try the same command
- It will create bundle.js in dist folder.
- Right click on dist folder and Include in project.
- Give the bundle.js file path in Index.cshtml view page.
<script src="~/../dist/bundle.js"></script>
Now the react components will get integrated with our Index.cshtml file.
CONCLUSION
- Likewise we can Integrate Angular and Vue js with ASP.NET MVC Razor pages.
[…] https://athen.tech/integerate-react-js-with-asp-net-mvc/ […]