I am one to think that not everything I build has to be a Single Page Application (SPA). Recently I was building a project for a client, and I decided that only one section of the app needed to be a SPA and the rest of the app a "traditional" MVC app, so I started the app with the "MVC" part and later added the "SPA". This is how I did it.
Adding a React app to your existing .NET Core MVC app is easier than you might think
One thing to note is that I am using VS Code and the .NET Core CLI on macOS.
The Existing .NET Core MVC App#
If you wish to follow along, clone the following repo dotnet-core-mvc-react (intial-app branch. Yes, branch name is misspelled >_<) and open the project.
To run the project in VS Code, open the integrated terminal and type the following
Our awesome app has three views under
Home controller and configured with a custom 404 page.
You get a new feature request and it is a perfect candidate for a React app. Fortunately, adding a React app is easier than you might think.
Go ahead and stop the project (if you have it running) by pressing
Ctrl + C in your terminal.
Creating the React app#
Rather than creating the app from scratch or using Create React App (CRA), we will create a new .NET Core project with React template. This default template will have React Router installed making it easier for us.
Open your terminal, navigate to a different directory and type the following
Now in Finder navigate to this newly created project directory (temp-react-core) and copy ClientApp directory to the root of our actual project. Also copy
WeatherForecastController.cs to the Controllers directory and
WeatherForecast.cs to the Models directory of our project.
You will end up with the following project structure.
Now back to VS Code, open
WeatherForecast.cs and change the namespace to match our project's namespace. You will end up with the following
Still in VS Code, open
dotnet-core-mvc-react.csproj and replace it with the following contents