11 Feb

Getting Started with React.js in ASP.NET MVC

In this post we will learn how to Getting Started with React.js in ASP.NET MVC.

What is React?

React is a UI library developed at Facebook. It is a Javascript library for building user interfaces. It is used by Facebook and Instagram. JSX is the extension for the React.

React provides two features

  1. Rendering DOM (Rendering the model to the DOM and keeping the DOM synchronized with changes to the model).
  2. Events.

Top Feature

  • React top feature is SPEED.

You can check or compare the react js performance features here http://chrisharrington.github.io/demos/performance/

What is JSX?

It is a Javascript XML syntax transform. JSX supports xml like syntax inline in javascript. Each element is converted into a javascript function call. http://facebook.github.io/react/jsx-compiler.html

jsx

JSX

Components

A react consists of set of components.

  • PROPS
  • STATE

The inputs to the components are referred as properties called as props and state, the difference between two is the state can change at any time.

To render an any element we use renderComponent method.

Example for renderComponent

React.renderComponent(
  <h1>ReactJS.Net in ASP.NET MVC 5</h1>,
  document.getElementById('myDiv')
);

In the above syntax, the first argument is the component we want to render, the second argument is the DOM node it should bind to. We can use the createClass method to create custom component classes. It takes an object of specifications as it’s argument.

Example for renderClass

var Component = React.createClass({
    render: function(){
        return (
            <h1>Hello, world!</h1>
        );
    }
});

After creating a class we can render it in our html document

React.renderComponent(
    <Component/>,
    document.getElementById('myDiv')
);

ReactJS.NET

ReactJS.NET makes it easier to use Facebook’s React and JSX from C# and other .NET languages, focusing specifically on ASP.NET MVC. It supports on-the-fly JSX to JavaScript compilation, also bundling and minification.

Create an  ASP.NET MVC Application

Reactjs project
Install React.js and ReactJS.NET from the Nuget console package manager by the following command Package Manager Console

PM> Install-Package react.js

Now install ReactJS.NET (MVC 4 and 5)

PM> Install-Package React.Web.Mvc4

Now reference the React.js reference in Index.cshtml file

@section Script{
    <script src="~/Scripts/react/react-0.12.2.min.js"></script>
}

Hello World Example

Create HelloWorld.jsx in the scripts folder.

helloworldjsx

Now add the HelloWorld.jsx in the View page.

 <script src="@Url.Content("~/Scripts/HelloWorld.jsx")"></script>

Now we will create a component that renders Hello World. Before that we create a div  with id container in the index page to bind the Hello World.

<div id="content"></div>

HelloWorld.jsx

var App = React.createClass({
	render: function(){
		return(
			<h1> Hello World! </h1>
		);
	}
});

React.render(<App/>, document.getElementById('content'));

 Display Data From the server side or controller

Now Create a ActionMethod that will returns static message in the ReactJS Controller.

public class ReactJSController : Controller
{
    // GET: ReactJS
    public ActionResult Index()
    {
        return View();
    }


    public JsonResult GetMessage()
    {
        return Json(new { result = "Hello World From ReactJS Controller" }, JsonRequestBehavior.AllowGet);
    }
}

Now get the data in to the component and render it into the div.

 var App = React.createClass({

		getInitialState: function(){
			return{data: ''};
		},

		componentWillMount: function(){
		var xhr = new XMLHttpRequest();
		xhr.open('get', this.props.url, true);
		xhr.onload = function() {
		  var response = JSON.parse(xhr.responseText);

		  this.setState({ data: response.result });
		}.bind(this);
		xhr.send();
	},

        render: function(){
            return(
                <h1>{this.state.data}</h1>
            );
        }
});

React.renderComponent(<App url="/ReactJS/GetMessage" />, document.getElementById('content'));

Output

reactjsoutput

Getting Started with React.js in ASP.NET MVC

 Source Code:

You can download the source from the Github

 

 

3 thoughts on “Getting Started with React.js in ASP.NET MVC

  1. Thank you for this. I’ve waded through countless useless “getting started” ReactJS tutorials, and this is the first one that simply communicated exactly what I needed (grabbing data from the server in a straightforward way, then just rendering it). All the others I’ve seen have just gone overboard with a bunch of unnecessary complications and flourishes. Funny how your short tutorial quickly gave me the knowledge I needed, all the others just had me shaking my head.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>