Getting Started React.js In MVC

React.js

React is an open source JavaScript library, created by Facebook to build complex, interactive UI in Web and mobile Applications. It is considered as the V in MVC. It is currently one of the most popular JavaScript libraries and it has a strong foundation and large community behind it.

Advantage of React.js,

  1. React uses virtual DOM, which is JavaScript object. This will improve app performance, since JavaScript virtual DOM is faster than the regular DOM.
  2. React can be used on client and Server side.
  3. Component and Data patterns improves the readability, which helps to maintain larger apps.
  4. React can be used with other frameworks.

Getting Started,

  • Create a new Project. Open Visual Studio 2015.
  • Go to File -> New -> Project.
  • Select Web in the installed templates.
  • Select ASP.NET MVC 5 Web Application.
  • Enter the name and choose the location.
  • Click OK.

Right click on your solution and click Manage NuGet Package Manager, as shown below-

Nuget package Manager
Now, search React.Web.Mvc4 and click Install button.

Install

Now, let’s create a new JavaScript file and give the extension .JSX, as given below-

JavaScript file

Add code in .JSX file, as given below-

  1. var Articles = React.createClass  
  2. ({  
  3.     render: function()   
  4.     {  
  5.         return ( < div className = "article" > < h1 > Fav Articles < /h1>  < ArticleList / > < ArticleForm / > < /div> );  
  6.     }  
  7. });  
  8. var ArticleList = React.createClass  
  9. ({  
  10.     render: function()   
  11.    {  
  12.         return ( < div className = "articleList" > Hello, World!Article List. < /div> );  
  13.     }  
  14. });  
  15. var ArticleForm = React.createClass  
  16. ({  
  17.     render: function()  
  18.   {  
  19.         return ( < div className = "articleForm" > Hello, World!Article Form. < /div> );  
  20.     }  
  21. });  
  22. ReactDOM.render( < Articles / > , document.getElementById('content'));  
If you want to render only one var, write, as given below-
  1. ReactDOM.render  
  2. (  
  3.   React.createElement(ArticleForm, null  
  4. ),   
  5.   document.getElementById('content'));  
Now, add references of. JSX file and other supporting Java scripts.
  1. @{  
  2. ViewBag.Title = "Index";  
  3. Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5. <script src="~/Scripts/React/react.min.js"></script>  
  6. <script src="~/Scripts/React/react-dom.min.js"></script>  
  7. <script src="~/Scripts/React/JSXTransformer.js"></script>  
  8. <script src="~/Scripts/articles.jsx" type="text/jsx"></script>  
  9. <div id="content"></div>  
Output

Output

Conclusion

This blog shows the basic starting part of React.JS in MVC. In my next articles,  we will learn deeply about React.JS. If you have any question or comments, drop me a line in C# Corner comments section.

 

Ebook Download
View all
Learn
View all