Razor To React

Part 2

Part 1 is here

To recap the aim is to see if I can remove existing Razor syntax from mvc.net views and replace it with a javascript view framework without having to rewrite the server side .net code

The challenge is to see how easily and succinctly can the following syntax be replaced

foreach (var order in @Model.PurchaseOrders)
{
 <div class="col-md-6">Requisition: @order.Id</div>
 <div class="col-md-6 ">Date created: @order.DateCreated.ToShortDateString()</div>
}

In part 1 I was able to replace Razor fairly easily but due to my misconceptions the code was unnecessarily verbose.

After some sage advice I came up with the following React jsx


var RequisitionBox = React.createClass({
 getInitialState: function() {
 return { requistionData: this.props.initialData };
 },
 render() {
 var requisitionNodes = this.state.requistionData.map(requisition =>
 <Requistion Id={requisition.Id} DateCreated= 
                 { requisition.DateCreated}></Requistion>
 );

 return (
 <div className="requisition">
 <h1>Requistions List</h1>
 <div className="requisitionList">{requisitionNodes}
 </div>
 </div>
 );
 }
});

var Requistion = React.createClass({
 render() {
 return (
 <div> 
 <div className="col-md-6 "> Requistion:{this.props.Id}</div>
 <div className="col-md-6 ">{this.props.DateCreated}</div>
 </div>

 );
 }
});

The main difference now is that the React script is no longer handling the fetching of the data from the server. Instead we are now using server side rendering to pre-render the initial state of React components. The bonus of doing this is that it speeds up initial page load. To do this its as simple as

@Html.React("RequisitionBox", new { initialData = Model.PurchaseOrders})

Now we're cooking with gas. No new controller actions had to be created . No Ajax or DOM manupilation was involved. Simply render the specified React component and give it your model data. Even though the React script could be compressed into a single class to make it more succinct - however I think its better to break it into small components even if its more verbose.

Part 3 Journey into TypeScript.