Complete Guide to using ASP.NET Core with React

Complete Guide to using ASP.NET Core with React

19 Jun 2024
Intermediate
1.32K 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

Q1. What is react?

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

Q2. Can I use React with ASP.NET Core?

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.

Q3. Which is better with .NET Core angular or React?

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

Q4. Is React and .NET a good combination?

React and .NET are a good combination that helps in creating high-performing applications with powerful front end and scalable back end.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingOct 26SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingOct 27SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this