27
DecComplete Guide to using ASP.NET Core with React
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
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
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
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
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
Read More: |