Contents
data/authors/Paul Logan.json

Introducing React to an existing ASP.Net MVC 5 app

Contents

This is the first post in a new series.

I have returned to an application I developed a number of years ago to add some new functionalities. It was developed as a .Net MVC application - all the views were created as server side rendered .CSHTML pages and there was a good bit of plain old Javascript and jQuery.

Tech Stack
  • ASP.Net MVC 5 framework
  • C#
  • Entity Framework 6
  • Javascript & jQuery

I wanted to make use some of the coding practices from my more recent projects.

  • A full on templating library. I had used Handlebars and Knockout.js - both of these were a joy to work with compared to using document.importNode and appendChild.

  • A JavaScript library/framework to take care of the plumbing code. The project used a homegrown javascript library developed by the original software developer - much more advanced than the one I had started developing before I discovered Knockout.js. Unfortunatley, this meant there was no documentation and no on-line community for help and further development.

React.js seemed like a good option - allowing me to apply the library to select parts of the application.

Installing React.js in an ASP.NET MVC project

React is famous for building SPA applications, but I am working on an existing system, so I followed the useful instructions here.

  • From Windows Terminal, browse to project root and execute the following two commands:

    • npm init -y /posts/introducing-react-to-existing-mvc-app/npmInit.png

    • npm install babel-cli@6 babel-preset-react-app@3 /posts/introducing-react-to-existing-mvc-app/npmInstallBabel.png

  • Create a src folder in your project root.

    Folder for React scripts in VS Solution Explorer
    Folder for React scripts in VS Solution Explorer

  • Add a new .cshtml View file including the following two script tags

	<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
	<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
  • Run JSX Preprocessor by executing this command in the Windows Terminal
npx babel --watch src --out-dir ./Scripts/ReactjsMVC --presets react-app/prod
/posts/introducing-react-to-existing-mvc-app/jsxPreprocessor.png

And that’s is - React has generated a “processed” js file based on the one we created in the src folder.

(Be sure to click on the “Show All Files” button at the top of the Solution Explorer to see the js file that was generated and right-click the file and Include In Project)

/posts/introducing-react-to-existing-mvc-app/reactGeneratedJsFile.png

Our old-school MVC app is now using the modern javascript React library!

Regards,

Paul.