Complete Guide to using ASP.NET Core with React

Complete Guide to using ASP.NET Core with React

19 Jun 2024
Intermediate
1.75K Views
10 min read

ASP.NET Core with React

Both ASP.NET Core and React are powerful technologies. React is a popular JavaScript library, whereas ASP.NET Core is a high-performing framework. Combining ASP.NET Core with React leads to powerful, efficient, and scalable web applications.

In this ASP.NET Core Tutorial, we are going to learn how useful it is when combined, ASP.NET Core with React. We will also create a project with the help of these technologies. To learn more about various other core concepts of ASP.NET, enroll in our ASP.NET Certification Training.

What is React?

React is a well-known JavaScript library that is used specifically for single-page applications to create user interfaces.

  • It was created by Facebook and is based around components, which can enable developers to put together components that take care of their state and then construct complex user interfaces using them.
  • The virtual DOM in React ensures intelligent upgrades that are faster and more efficient than the direct manipulation of the latter.
Read More: React Core Concepts: State, Props, Virtual DOM, Events and Refs

What is ASP.NET Core?

The ASP.NET Core framework is a high-performance, all-in-one system for developing modern, internet-enabled, cloud-based applications. It is supported on multiple platforms.

  • Unlike the old ASP.NET, it has been rebuilt to be lightweight and easily separable from other systems.
  • It remains an ideal choice for server-side applications or APIs because it can run under Windows, Mac OS, or Linux servers.
  • It goes well with many of the web's current popular frameworks by using such technologies as MVC, Razor Pages, and Blazor.

Benefits of Using ASP.NET Core with React

Combining ASP.NET Core with React offers several advantages:

  • Performance and Scalability-ASP.NET Core's high performance and React's efficient rendering provide a robust foundation for scalable applications.
  • Cross-Platform Development- ASP.NET Core and React are known for their cross-platform development capabilities, which means that you can develop applications with these two technologies on Windows as well as macOS and Linux machines.
  • Separation of Concerns—If you use React for the front end and ASP.NET Core for the back end, you can maintain them separately. This will ensure that your code base is manageable and understandable enough for developers.
  • Rich Ecosystem-Both technologies have big ecosystems and communities; they provide a wealth of libraries, tools, and resources; thus, they help speed up development.

Setting Up the Development Environment

To start, we should establish a development environment. This means installing the required tools, creating a new ASP.NET Core project, and setting up a React app.

1. Installing Required Tools

First, we need to install the following tools:

  • Node.js- Node.js is required to run React and manage dependencies.
  • .NET SDK- The .NET SDK is required to develop and run ASP.NET Core applications.
  • Visual Studio Code- A popular code editor that supports both React and ASP.NET Core development

2. Creating a New ASP.NET Core Project

Open a command prompt or terminal and use the command below to create a new ASP.NET Core project after getting the tools installed:

dotnet new webapi -n AspNetCoreReactApp
cd AspNetCoreReactApp

This will create a new ASP.NET Core Web API project located in a directory named AspNetCoreReactApp.

3. Setting Up a React App

Next, we need to set up a React app. In the AspNetCoreReactApp directory, run the following commands:
npx create-react-app client-app
cd client-app

This creates a new React application in a subdirectory named client-app.

Building the Backend with ASP.NET Core

Now that our project structure is set up, let's build the backend using ASP.NET Core.

Open the AspNetCoreReactApp directory in Visual Studio Code. In the Controllers folder, create a new file named WeatherForecastController.cs with the following content:

using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreReactApp.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        public class WeatherForecast
        {
            public DateTime Date { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }
        }
    }
}

A simple API endpoint is provided by this controller that returns a list of weather forecasts.

Read More: Salary Offered to ASP.NET Developers

Building the Frontend with React

Next, let's build the front end using React.

Open the client-app directory in Visual Studio Code. In the src folder, create a new file named WeatherForecast.js with the following content:

import React, { useState, useEffect } from 'react';

function WeatherForecast() {
    const [forecasts, setForecasts] = useState([]);

    useEffect(() => {
        fetch('/weatherforecast')
            .then(response => response.json())
            .then(data => setForecasts(data));
    }, []);

    return (
        <div>
            <h1>Weather Forecast</h1>
            <ul>
                {forecasts.map((forecast, index) => (
                    <li key={index}>
                        {forecast.date}: {forecast.temperatureC} °C - {forecast.summary}
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default WeatherForecast;

It is responsible for getting data from the WeatherForecast API point and showing it.

ASP.NET Core with React.js Example

To integrate the React frontend with the ASP.NET Core backend, update the Startup.cs file in the AspNetCoreReactApp directory as follows:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapFallbackToFile("index.html");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "client-app";

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
}

This setup configures the React development server and clears the path for proper routing of API calls.

Conclusion
Now that you have learned how ASP.NET Core and React can be combined to create strong efficient web applications that take advantage of the two technology’s benefits, get into our ASP.NET Certification Course and know more about these concepts.
Read More: 

FAQs

React is a JavaScript library that is used to create user interfaces specifically the single page applications.

Yes, React can be used with ASP.NET Core to create more scalable and powerful applications using React for the front end and ASP.NET Core for the back end.

Both Angular and React work well with .NET Core. The choice depends on the requirements of your project.

React and .NET are a good combination that helps in creating high-performing applications with powerful front end and scalable back end.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this