I am exploring writing single page applications with React on the front end and .NET on the backend (and I am new to both, so apologies if the questions seem simple!). I am using Visual Studio for Mac.
In order to start simple, all my backend code does is returns "Hello, (name of person)" e.g. "Hello, Bob". However, I want the name of the person to be whatever a user inputs into the React form on the web page.
.NET Controller:
namespace TestingReactDotNet.Controllers
{
[Route("api/[controller]")]
public class DisplayNameController : Controller
{
[HttpGet, Route("Greeting")]
public string Greeting(string name)
{
var greeting = "Hello" + name;
return greeting;
}
}
}
React file (DisplayName.js):
import React, { Component } from "react";
export class DisplayName extends Component {
state = {
name: "",
greeting: ""
};
updateInput(key, value) {
this.setState({
[key]: value
});
}
calculate(){
fetch("api/DisplayName/Greeting")
.then(response => response.text())
.then(data => {
this.setState({ greeting: data });
});
<h1>this.state.greeting</h1>
}
render() {
return (
<center>
<div className="App">
<div>
Type a word...
<br />
<input
type="text"
placeholder="Type word here ..."
value={this.state.name}
onChange={e => this.updateInput("name", e.target.value)}
/>
<button onClick={() => this.calculate()}>Submit</button>
<br />
</div>
</div>
</center>
);
}
}
My question is:
- How do I get the frontend and backend to talk to each other here, so that whatever name the user inputs into the form, the DisplayName method can use in order to return the string which is then displayed on the page?
I appreciate it's probably easier just to do this using React alone, but I am really trying to ensure that I can use React and .NET together, so any advice is really appreciated.
Thanks :)