Skip to main content

Create a React App with Visual Studio 2017 and ASP.NET Core 2.2

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).

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.

React App templates with Visual Studio 2017

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.

React App running in the browser

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.

React App with Visual Studio 2017 and ASP.NET Core 2.2

  • The ClientApp subdirectory is a standard React application so you can run npm commands such as npm test or npm install.
  • The src folder has various react components which build the UI layer.
  • In the ClientApp folder, you can see the main component App.js and its associated test suite (App.test.js).
  • Here, index.js provide an entry into the App and also kicks off the registerServiceWorker.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.

React app development server

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.

React app development server_1

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.

React app development server_not_running

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.

Publish the React App

Now right-click on the project and select Publish. Choose the publish target as Folder and provide the folder path.

Publish the React App-Steps

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.

Running React Application Directory

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,

    Deploy React App on IIS

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.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

11 thoughts to “Create a React App with Visual Studio 2017 and ASP.NET Core 2.2”

  1. 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.

  2. 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

    }

    )
    }
    }

  3. 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.

  4. 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.

  5. 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

Leave a Reply

Your email address will not be published. Required fields are marked *