A simple way to use the react frame work with ASP.NET

One of the most straightforward ways of working with .Net using react is to use .Net as API in the back end while React does what it does best.

In this article I’m going to demonstrate a simple example of this concept, we are going to use the Hook to create our react component, and the simple .Net core API for our back end, I’m also going to use Swagger to test the API.

Creating a simple API in .Net

 

public class LoginController : Controller {

    namespace API_for_testing.Controllers
{
    [ApiController]
    [Route("test/[action]")]
    public class HomeController : Controller
    {
       [HttpGet]
        public string[] getStrings()
        {
            string[] test = { "This is test case 1", "This is test case 2", "This is test case 3" };
            return test;
        }

        [HttpPost]
        public string[] postStrings(string s)
        {
            string[] test = { "This is test case 1", "This is test case 2", "This is test case 3", s };
            return test;
        }
    }
}

 

Testing that the API is up and running.

       

 

Now on to the front end, since we are displaying a array of items, it would be a good idea to install an ID generator so we can give the items a key, I’m using UniId in this case.

       

 

Similar to a regular  Javascript app, we fetch the data from our API the fetch method  imported from the node-fetch library, the fetch method returns a  promise object that is the response of the get request made to our API, then we would store that promise in our state using the “set” method provided.

Then we would insert the data into JSX and return it, don’t forget to give the items a key using any id generator of your choice.

 

End result.

       

This has been a simple example of one of the ways to use React alongside .Net