In this post I'll walk through the way I found of implementing a React app into an ASP.NET project using .
1. Creating the project
Select your preferred ASP.NET template to start, or skip this part if you're using an existing application. Check out
3. Install webpack and webpack-cli
Go to View > Terminal to open the command line and enter these commands to install your project's packages and webpack:
cd <ProjectName>npm install webpack webpack-cli
4. Setup a webpack.config.js file and a babel.config.js file
I've used
And it has successfully created a bundled file in my Scripts folder:
9. Connecting both applications adding a Web API to the ASP.NET project
Create a new item in the project, and select Web API Controller Class:
This API will be your main connection between the ASP.NET project and the React app, so it works as a proper back-end for it.
Now we just need to configure the API route to get it running.
Add an API route to your RouteConfig.cs:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{action}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional, controller = "Values" }
);
I've used
I went to /api/get/1 as I configured, and it got the value, so it's working! Now it's time to pass this value to the React app so both projects are connected.
10. Making a request to your Web API in the React app
I'll add a simple GET request into my React app, set the value I got from the API in the state, and display it in the main page.
In my App.js:
import logo from './logo.svg';
import React, { Component } from "react";
import './App.css';
class App extends Component {
constructor() {
super();
this.state = { value: [] };
}
async getData() {
let resp = await fetch('/api/get/1',
{
method: "GET",
headers: {
'Content-Type': 'application/json'
}
});
if (resp.status === 200) {
let value = await resp.json();
return value;
}
}
async componentDidMount() {
let value = await this.getData();
this.setState({ value: value });
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<p>{this.state.value}</p>
</header>
</div>
);
}
}
export default App;
Done! The value I got from the ASP.NET Web API is showing in the React page.
Conclusion
This is my first article ever, I hope it helps people in some way, like I needed when I got the task to do this. Comment any suggestions or questions, feel free to reach out and I'll do my best to get back to you ;)

SOCIAL SHARE CARD GENERATOR