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

In this article, I have explained about how to create your first react application with ASP.NET Core Web application in Visual Studio 2017 with default react.js template, also explained about how to create new react component. React application can be used to develop Single Page Application (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 below screenshot. Click OK.

Note: Make sure .NET Core 2.2 SDK already installed to 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 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 default configuration required for React. Required react libraries in installed in the template. Build the application. While building/running the application as 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 into your machine.

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

Simple Example to Create New React Components

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

This example will walkthrough to create new component which will display the full name of user by getting first name and last name as input.

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

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

Import the React component

import React, { Component } from 'react';

Create new class User which extends react component

export class User extends Component{ }

Add constructor to initializes the state variables. This constructor will be called before render 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 user clicks the button. This button code added in Render block.

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

MyChangeHandler method will call when user enter data to input textbox, and we have code here to set the user entered value to 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 match.

<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 to App.js file. You can find App.js file in Src folder.

Import the User component in header

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

Add the Route and component in to 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 present in Src folder. Index.js file is the default file where react application will begin.

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

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

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

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

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

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

Step 1: Create 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 method. You can delete all the methods inside the controller class.

Create 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 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 new react component using the steps which i already mentioned above. I have created new Customer.js component under 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 state variable as array of list.

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 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 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 navigation menu NavMenu.js like we done for creating new component section we read earlier.

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

Step 8: Refer 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 the knowledge to on how to create 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 application using Angular in Visual Studio,

Advertisements

Leave a Reply