How to Create your First React Application with .NET Core in Visual Studio 2017 with Simple Example?

How to Create your First React Application with .NET Core in Visual Studio 2017 with Simple Example?

In this article, I have explained how to create your first react application with ASP.NET Core Web application in Visual Studio 2017 with default react.js template, also explained how to create a new react component. React application can be used to develop Single Page Applications (SPA).

Follow the below steps to start creating on React application.

Step 1: File -> New -> Project.

Step 2: Select Web -> ASP.NET Core Web Application. Enter the Project Name. Here I have named as “MyFirstReactApp”. Click OK.

Step 3: Chose the .NET Core version, under which you want to create React Application. Here I have chosen ASP.NET Core 2.2.  Select React.js Template as shown in the below screenshot. Click OK.

Note: Make sure .NET Core 2.2 SDK is already installed on your machine. If not, you can install this using the below download link.

64 Bit: https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.2.108-windows-x64-installer

32 Bit: https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.2.108-windows-x86-installer

To use a higher version like Core 3.0, you need to use Visual Studio 2019.

Step 4: That’s it. You have done the creation of your First React Application with .Net Core 2.2 in Visual Studio 2017.

Step 5: Check the Solution Explorer. All project-related files are created with the default configuration required for React. Required react libraries in installed in the template. Build the application. While building/running the application for the first time, it takes time to download and install some required NPM packages.

Note: If you don’t install Node.js. You need to install it to run the React application. To install the Node.js, download the recommended installer from this link https://nodejs.org/en/, then install it into your machine.

Step 6: After a successful build, run the application, you will get the following output in the browser,

Simple Example to Create New React Components

Here, I have explained how to create a new component with a simple example in React application. Follow the below steps.

This example will walk through to create a new component that will display the full name of the user by getting first name and last name as input.

Step 1: Navigate to ClientApp -> src -> components. Create a new JavaScript file called “User.js” under the component folder. You can find other components of JavaScript files under this folder.

Step 2:  Write the below code in User.js file. I have explained key things to consider,

Import the React component

import React, { Component } from 'react';

Create a new class User which extends react component

export class User extends Component{ }

Add a constructor to initialize the state variables. This constructor will be called before rendering the DOM.

Here we have defined three state variables First Name, Last Name, and Full Name.

constructor(props) {
       super(props);
        	this.state = { firstname: '', lastname: '', fullname: '' };
       }

Add method to append First Name and Last Name values and set to Full Name state variable.

DisplayFullName = () => {
     this.setState({ fullname: this.state.firstname + " " + this.state.lastname }); 
}

This DisplayFullName method will be called when the user clicks the button. This button code was added in the Render block.

<button type="button" onClick={this.DisplayFullName} class="btn btn-primary">Display Full Name</button>

MyChangeHandler method will call when the user enters data to input textbox, and we have code here to set the user entered value to the state variable.

myChangeHandler = (event) => {
        let nam = event.target.name;
        let val = event.target.value;
        this.setState({ [nam]: val });
    }

<input type="text" name="firstname" onChange={this.myChangeHandler} placeholder="Enter First Name" />

Define the DOM render block, here we write HTML code.

Input Text box name and state variable name should be matched.

<input type="text" name="firstname" onChange={this.myChangeHandler} placeholder="Enter First Name" />

this.state = { firstname: '', lastname: '', fullname: '' };

Find the Complete Code of User.js file:

import React, { Component } from 'react';

export class User extends Component {
    static displayName = User.name;

    constructor(props) {
        super(props);
        this.state = { firstname: '', lastname: '', fullname: '' };
    }

    DisplayFullName = () => {
        this.setState({ fullname: this.state.firstname + " " + this.state.lastname });
    }

    myChangeHandler = (event) => {
        let nam = event.target.name;
        let val = event.target.value;
        this.setState({ [nam]: val });
    }

    render() {
        return (
            <div>
            <h1>Display User's Full Name</h1> <br />
            <form>
                <div class="row">
                    <div class="col-sm-2">
                        <label>First Name: </label>
                    </div>
                    <div class="col-sm-6">
                            <input type="text" name="firstname" onChange={this.myChangeHandler} placeholder="Enter First Name" />
                    </div>
                </div>
                <br />
                <div class="row">
                    <div class="col-sm-2">
                        <label>Last Name: </label>
                    </div>
                    <div class="col-sm-6">
                            <input type="text" name="lastname" onChange={this.myChangeHandler} placeholder="Enter Last Name" />
                    </div>
                </div>
                <br />
                <div class="row">
                      <div class="col-sm-6">
                          <button type="button" onClick={this.DisplayFullName} class="btn btn-primary">Display Full Name</button>
                      </div>
                </div>
                </form>
                <br />
                <div class="row">
                    <div class="col-sm-2">
                        <label>Full Name: </label>
                    </div>
                    <div class="col-sm-6">
                        {this.state.fullname}
                    </div>
                </div>
            </div>
        );
    }
}

Step 4: Need to include the above newly created component into App.js file. You can find the App.js file in the Src folder.

Import the User component in the header

import { User } from './components/User';

Add the Route and component to the render block.

<Route path='/user' component={User} />

Find the Complete Code of App.js file:

import React, { Component } from 'react';
import { Route } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
import { User } from './components/User';

export default class App extends Component {
  static displayName = App.name;

  render () {
    return (
      <Layout>
        <Route exact path='/' component={Home} />
        <Route path='/counter' component={Counter} />
        <Route path='/fetch-data' component={FetchData} />
        <Route path='/user' component={User} />
      </Layout>
    );
  }
}

Note: This App.js Component is rendered to Index.js file which presents in the Src folder. Index.js file is the default file where react application will begin.

Step 5: Add User component routing link in the navigation menu. Add the below code in NavMenu.js file under the components folder.

<NavItem>
     <NavLink tag={Link} className="text-dark" to="/user">Users</NavLink>
</NavItem>

Note: the react-router-dom library will be used for routing purposes.

Step 6: Now build and run the application. You can see the new link “Users” added in the menu. Click on this to open the user page.

Step 7: If you give First Name and Last Name as input then click on the Display Full Name button, you will get the result.

How to Bind Data from API to Components in the React Application?

Step 1: Create a new API Controller under Controller folder, here I have created new API controller named “CustomerAPIController”.

Step 2: New API controller will be created with some default get and post methods. You can delete all the methods inside the controller class.

Create a new HttpGet action method which will be used to write the business logic to get all the customer data from any data source.  Here, for example, I have initialized some local data using a list object. You can modify this to get the data from Database.

Find the complete code in API Controller:

namespace MyFirstAngularApp.Controllers
{
    [Route("api/[controller]")]
    public class CustomerDataController : Controller
    {
        [HttpGet("[action]")]
        public IEnumerable<Customer> GetCustomerData()
        {
            Customer customers = new Customer();
            return customers.GetCustomer();
        }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }

        List<Customer> CustomerList = new List<Customer>();

        public Customer() { }

        public List<Customer> GetCustomer()
        {
            //Initialize 10 dummy customer id's and names. 
            for (int count = 1; count <= 10; count++)
            {
                Customer customerData = new Customer()
                {
                    Id = count,
                    Name = "Name " + count
                };
                CustomerList.Add(customerData);
            }
            return this.CustomerList;
        }
    }
}

Step 3: We should create a new react component using the steps that I already mentioned above. I have created a new Customer.js component under the components folder.

Step 4: Write a code to fetch the data from API get action in Customer.js file.

Written fetch data code inside the constructor. This will fetch the customer data from the API method we have created above. API responses will be stored in JSON format then added to the state variable as an array of lists.

constructor(props) {
        super(props);
        this.state = { customerData: [], loading: true };

        fetch('api/CustomerAPI/GetCustomerData')
            .then(response => response.json())
            .then(data => {
                this.setState({ customerData: data, loading: false });
            });
}

Created a method to parse the response data and construct the table element. Map method used to iterate the values in JSON array.

static renderCustomerTable(customers) {
        return (
            <table className='table table-striped'>
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    {customers.map(customer =>
                        <tr>
                            <td>{customer.id}</td>
                            <td>{customer.name}</td>
                        </tr>
                    )}
                </tbody>
            </table>
        );
}

Note: Response data variables should be used in the first letter smaller case.

Call the method in render block.

Customer.renderCustomerTable(this.state.customerData);

Find the complete code in Customer.js:

import React, { Component } from 'react';

export class Customer extends Component {
    static displayName = Customer.name;

    constructor(props) {
        super(props);
        this.state = { customerData: [], loading: true };

        fetch('api/CustomerAPI/GetCustomerData')
            .then(response => response.json())
            .then(data => {
                this.setState({ customerData: data, loading: false });
            });
    }

    static renderCustomerTable(customers) {
        return (
            <table className='table table-striped'>
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    {customers.map(customer =>
                        <tr>
                            <td>{customer.id}</td>
                            <td>{customer.name}</td>
                        </tr>
                    )}
                </tbody>
            </table>
        );
    }

    render() {
        let contents = this.state.loading ? <p><em>Loading...</em></p> : Customer.renderCustomerTable(this.state.customerData);

        return (
            <div>
                <h1>Customer Data</h1>
                {contents}
            </div>
        );
    }
}

Step 6:  Then add this Customer component to App.js and then add the Customer link in the navigation menu NavMenu.js like we have done for creating the new component section we read earlier.

Step 7: That’s it, Build and Run the application.

Step 8: Refer to the Output screenshot,

Conclusion

I hope this article helps you to understand the programming in React application and walked thorough you to create your first React Application in Visual Studio 2017. Also, you get knowledge on how to create a new simple react component and how to fetch the data from APIs.

To get the comparison guide about Angular vs React vs Vue.

You can also read the below article to learn about how to create applications using Angular in Visual Studio,

He is a product manager at a reputed software company and a freelance blog writer. He is experienced in different technologies, web securities, and web applications. He keeps learning and make himself up to date on the latest technologies, news, health, and fitness. This encouraged him to share his experiences by writing articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top
%d bloggers like this: