React is a component-based JavaScript library for building user interfaces. It lets you create the view layer from small and isolated pieces of code called components. Earlier, I posted about creating Angular 5, Angular 6 and Angular 7 apps with Visual Studio 2017 and ASP.NET Core. Similarly, the ASP.NET Core SPA templates allow you to create a React App with Visual Studio 2017 and ASP.NET Core 2.2 without installing any third-party extensions or templates.
React App with Visual Studio 2017 and ASP.NET Core 2.2
If you want to learn React the right way, I want to personally recommend FullStack React as the single-best resource out there. It is the up-to-date, in-depth, complete guide to React and friends. You can get a copy here.
Before we begin, please do the following installation (ignore if already done).
- .NET Core SDK for 2.2.0-preview2 — includes ASP.NET 2.2.0-preview3
- Install Visual Studio 2017 15.9 Preview 5
- Node.js and npm latest version
Open Visual Studio 2017, hit Ctrl+Shift+N and select the ASP.NET Core Web Application (.NET Core) project type from the templates. When you click Ok, you will get the following prompt. Select ASP.NET Core 2.2 and choose the React template.
As you can see, there are 2 pre-defined templates for creating a React application. The difference between these templates is, the React.js And Redux template has Redux configured for you. For those who don’t know about Redux, it’s a predictable state container for JavaScript apps and helps you manage the data you display and how you respond to user actions.
Hit “OK” and build the application. Once build successfully, just run the app to see it in action. You should see the following.
Let’s take a close look at the application structure and how ASP.NET Core is running this react app.
React Application Structure
Below is a screenshot of the react application structure.
- The
ClientApp
subdirectory is a standard React application so you can runnpm commands
such asnpm test
ornpm install
. - The
src
folder has various react components which build the UI layer. - In the
ClientApp
folder, you can see the main componentApp.js
and its associated test suite (App.test.js
). - Here,
index.js
provide an entry into the App and also kicks off theregisterServiceWorker.js
. This service worker takes care of caching and updating files for the end-user.
Here, we’ll not be looking at the code of every react component. But, the FetchData.js
component is worth to mention. This component calls the ASP.NET Core Web API in the constructor to get the weather forecast and the set the state to display the list.
export class FetchData extends Component { displayName = FetchData.name constructor(props) { super(props); this.state = { forecasts: [], loading: true }; fetch('api/SampleData/WeatherForecasts') .then(response => response.json()) .then(data => { this.setState({ forecasts: data, loading: false }); }); }
Every React components implement a render()
method that takes input data and returns what to display. The component can maintain internal state data (accessed via this.state
). When a component’s state data changes, the rendered markup will be updated by re-invoking render()
.
The FetchData
component’s render method passes the state to the another static method which renders the weather forecast list.
render() { let contents = this.state.loading ? <p><em>Loading...</em></p> : FetchData.renderForecastsTable(this.state.forecasts); return ( <div> <h1>Weather forecast</h1> <p>This component demonstrates fetching data from the server.</p> {contents} </div> ); }
How ASP.NET Core running this application
The ASP.NET Core runs this react app differently in the development mode and production mode. In development mode, the react development server runs in background automatically, so your client-side resources are dynamically built on demand and the page refreshes when you change any file. To understand it better, execute the dotnet run
command, you’ll notice that the react development server runs by ASP.NET Core SPA services.
This is due to the code written in the Startup.cs
class’s configure
method. The UseSpa
middleware runs the react development server in development mode.
app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } })
So every time you run the application, the react development server runs in the background. This increases the compile time for the application. The other problem is, in case of any C# code change, we need to restart the application and which will also restart the react development server. To speed up things, the react development server can be run as a standalone process. You can connect to it from the ASP.NET Core application. To do that, navigate to the ClientApp
directory on command prompt and run npm start command to start the react development server.
Copy the development server URL from the command prompt, and replace the following line in the Startup.cs
,
spa.UseReactDevelopmentServer(npmScript: "start");
with,
spa.UseProxyToSpaDevelopmentServer("http://localhost:3000");
Execute the dotnet run
command and you will notice it no longer starts the react development server in the background.
In production mode, development-time features are disabled, and your dotnet publish
configuration produces minified, efficiently bundled JavaScript files. Take a look at the ConfigureServices
method code in the Startup.cs
class.
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); }
The above code tells that in production mode, the react files will be served from the ClientApp/build
directory. And this directory should be created once the application is published. So, let’s publish the application and deploy it on IIS.
Publish and Deploy on IIS
To publish the application first, change the environment to Production and set the configuration to Release mode.
Now right-click on the project and select Publish. Choose the publish target as Folder and provide the folder path.
Once the application is published, navigate to the published folder and you will find the build folder created inside the ClientApp folder (as mentioned in the Startup.cs
file). You can run the published app directly to find out no errors in published code. Run dotnet <dllName>
command to run the app directly.
Before starting the deployment, make sure .NET Core 2.2 Runtime & Hosting Bundle is installed. Now, let’s deploy the application on IIS.
- First, create an application app with No managed code.
- Add a new website named “ReactApp”, select the newly added application pool and provide the path of the published folder. Don’t forget to change the port number as 80 is reserved for default website. Like,
That’s it. You can browse the application and the react application should be running successfully in the browser.
Learn React the right way via FullStack React. It is the up-to-date, in-depth, complete guide to React and friends. You can get a copy here.
Summary
React is one of the most popular JavaScript library for building fast and interactive UI’s. It only deals with the View component of MVC (Model – View – Controller). This post talks about creating, publishing and deploying a React app with Visual Studio 2017 and ASP.NET Core 2.2. We also saw how ASP.NET Core runs the react development server and how to disable it for better performance.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.
The IIS deployment instructions didn’t work for me.
HTTP Error 500.19 – Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
import React, { Component } from ‘react’;
class App extends Component {
constructor()
{
super();
this.state = {
data: null,
}
this.getData();
}
getData()
{
let data= fetch(‘https://data.cityofnewyork.us/api/views/25th-nujf/rows.json’).then((resp) =>{
resp.json().then((res)=>{
console.log(res.view);
this.setState({data:res.view})
})
})
}
render() {
return (
{
this.state.data ?
this.state.data.map((item)=>
{item.name}
)
:
Wait… data is fetching
}
)
}
}import React, { Component } from ‘react’;
class App extends Component {
constructor()
{
super();
this.state = {
data: null,
}
this.getData();
}
getData()
{
let data= fetch(‘https://data.cityofnewyork.us/api/views/25th-nujf/rows.json’).then((resp) =>{
resp.json().then((res)=>{
console.log(res.view);
this.setState({data:res.view})
})
})
}
render() {
return (
{
this.state.data ?
this.state.data.map((item)=>
{item.name}
)
:
Wait… data is fetching
}
)
}
}
I have gotten this far, but nothing from `ClientApp\build` is being serverd, so no JS loads, and I just get a white screen.
same for me
Thanks for the article. It help me to understand how to create react app using visual studio.
This article is exactly what I was looking for. However, I am working in TypeScript and I would like to know if you can show us how it is done in Visual Studio 2017. Up to this point, I have been using “npm react-create-app my-app –typescript” command line to create my project.
Thank you for this great article on making react app in visual studio 2017 with asp.net core.I was searching for this article until I reached here. Can you also write the similar article on Angular 7 to. Thank you.
You can find the angular 7 article here..
https://www.talkingdotnet.com/create-an-angular-7-app-with-visual-studio-2017/
Great article! It would be nice to learn about how to do authentication with .NET Core and React. Thanks for writing these articles. They are big help for me
ditto here. more on authentication with .net core and react please ! Thanks !
Hey, I am a fresher developer working on .net and vue.js, It would really help me a lot if you publish an article using these two. Thank you