Feb 01, 2015

React.js: Introduction and Hello World with ASP.NET MVC 5

React.js is a JavaScript library for creating user interfaces by Facebook and Instagram. In this post, We will create a Hello World application and see how React.JS can be used with ASP.NET MVC 5. Here is the video tutorial of this post

React.js

React is a UI library to create interactive and reusable UI components. It is considered as the V in MVC.

It allows you to create your own components (NOT Templates like in AngularJS) that you can later reuse, combine, and nest to your content. Thus it will boost your productivity.

React.js is based on a concept called the Virtual DOM that determines what changes need to be made in the DOM beforehand and updates the DOM tree accordingly. Thus it avoids costly DOM operations and makes updates in a very efficient manner.

It is so easy to define and manipulate your own components by using a special syntax called JSX (Optional), which allows you to mix HTML/XML with JavaScript.

Check out Instagram for an example of a fully React based application.

ReactJS.NET

ReactJS.NET makes it easier to use React and JSX in .NET applications. It provides On-the-fly JSX to JavaScript compilation, Supports ASP.NET Bundling and Minification and allows you to pre-render the initial state of your React components server-side to make the initial load feel faster.

Getting started

Software versions used in the tutorial:

Visual Studio 2012

.NET 4.5

ASP.NET MVC 5.0

React.js 0.12.2

ReactJS.NET 1.3

Set up the Project:

1. Open Visual Studio > File > New Project > ASP.NET MVC 5 Empty Project, Call it "HelloWorldReact" > OK

2. Install React.js by running following command in the Package Manager Console

Install-Package react.js

It will add react javascript files in Scripts folder.

3. Similarly Install ReactJS.NET:

Install-Package React.Web.Mvc4

It will add react library references in the project.

4. Add MVC5 Empty Controller (HomeController.cs), Add View of Index method without Model.

Hello World

5. Add new folder jsx in Scripts folder, Create HelloWorld.jsx file and add following content:


var HelloWorld = React.createClass({
	render: function(){
		return (
			<div>Hello {this.props.name}</div>
			);
	}
});

React.render( <HelloWorld name="World" />, document.getElementById('container'));

6. Add jquery, react and jsx references in the view and add a container to display text. Here is the content of Index view:


@{
    ViewBag.Title = "Index";
}

<h2 id="container"></h2>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/react/react-0.12.2.min.js"></script>
<script src="~/Scripts/jsx/HelloWorld.jsx"></script>

When you run the app, you will get "Hello World". If you check HelloWorld.jsx file in Firebug or browser developer tools. you will get the compiled javascript file.


// @hash v2-61262DE4F1D888A8455C97131AEE25CB
// Automatically generated by ReactJS.NET. Do not edit, your changes will be overridden.
// Version: 1.3.0 (build dd748cc)
// Generated at: 2/1/2015 2:09:36 PM
///////////////////////////////////////////////////////////////////////////////
var HelloWorld = React.createClass({displayName: 'HelloWorld',
	render: function(){
		return (
			React.createElement("div", null, "Hello ", this.props.name)
			);
	}
});

React.render( React.createElement(HelloWorld, {name: "World"}), document.getElementById('container'));

Getting Data From Server Side

Add another action in HomeController which will return name


 public JsonResult GetName()
        {
            return Json(new { name = "World from server side" }, JsonRequestBehavior.AllowGet);
        }

We will use jQuery Ajax to get data from the server. Replace the code in HelloWorld.jsx file with the following code


var HelloWorld = React.createClass({

getInitialState: function() {
    return { name:''};
  },
componentDidMount: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
    render : function(){
        return (
        <div> Hello {this.state.name} </div>
        );
    }
});

React.render(
    <HelloWorld url="/home/getname" />,
    document.getElementById('container')
);

getInitialState() executes exactly once during the lifecycle of the component and sets up the initial state of the component.

componentDidMount is a method called automatically by React when a component is rendered. The key to dynamic updates is the call to this.setState(). We replace the old data with the new one from the server and the UI automatically updates itself.

When the state is updated, the component re-renders itself.

reactjs aspnet

Source Code

Conclusion

This post covered following things:

  • Brief introduction of React.js and ReactJS.net
  • Created a Hello World example
  • Implemented to get data from server side
  • Explained how to use React.js in ASP.NET MVC 5

In next post, we will do something interesting with React.js. Stay tuned and Enjoy React !!