Yesterday I made this sample "Hello World" program in React JS using Visual Studio 2017 to help everyone getting started with these two great technologies and understand how we can make them work together to develop a modern, responsive web site.
However, before digging through the code, it can be useful to spend a couple words about what React JS actually is.
What is React JS?
React JS is the popular language which contains front-end libraries that solve view and user interface problem of the web page. A react front-end library is created by Facebook to solve challenging view part of large websites built with MVC (Model view controller) Architecture.
React JS provide Virtual DOM because it knows the DOM manipulation is an expensive operation in any web page. When we want to change UI on our web page this provides a minimum number of DOM calculation for finding new state, from this DOM performance remain same on every change in the page. We can create custom UI components and render these components on a webpage with React because it provides unidirectional data flow in our mind with a simple top to bottom approach.
The "Hello World" sample
Now I will define how I have created this simple React JS Hello World program. There are some steps for creating the complete program:
Step 1: Create an MVC controller as HomeController.cs
Step 2: Add new action in your controller for getting the view, where we will implement our first React JS component.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Collection.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ReactWithMVCPart1.Controllers { public class HomeController:Controller { public ActionResultIndex() } } |
Step 3: Add new action in your controller for getting a view, where we will implement our first JS view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collection.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ReactWithMVCPart1.Controllers { public class HomeController:Controller { public ActionResult Index() { Return View(); } } } |
Step 4: Now it's time to add the view: an index.cshtml file which will contain the actual React JS code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
@{ ViewBag.Title = "Index"; } <h2>Hello World-React JS</h2> @*HTML for show reactjs component*@ <div id="helloworldcontainer"></div> @*Jquery library*@ <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> @*ReactJS Library*@ <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script> @*JSX converter(JSX to native javascript)*@ <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> @*Here we will create our first React JS components*@ <script type="text/javascript"> var HelloWorldComponent = React.createClass({ getInitialState : function() { return { serverMessage : '' }; }, componentDidMount : function() { //fetch data from server $.get('/home/getmessage', function(result) { if (this.isMounted) { this.setState({ serverMessage : result }) } }.bind(this)); }, Render : function() { return ("<h1>{this.state.serverMessage}</h1>") } }); ReactDOM.render( "<HelloWorldComponent />", document.getElementById("helloworldcontainer")); </script> |
Step 5: Add an another MVC action for return JSON data for showing in react JS component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using system.collection.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ReactWithMVCPart1.Controllers { public class HomeController:Controller { // add new action in your controller for getting a view, // where we will implement our first js view public ActionResult Index() { return View(); } // add another MVC action for return JSON data // for showing in react JS component public JsonResult getmessage() { return new JsonResult { Data="Hello World. I am from server-side", JsonRequestBehaviour= JsonRequestBehaviour.AllowGet }; } } } |
Step 6: Now debug and run program.
Error handling in React JS
Sometimes mistakes are in our program and these mistakes are called error and bugs for our program and we need to find, understand and fix these errors, these errors are in the number of ways for that our system scans all our program and then provide an incorrect outcome.
Errors are different in different type of languages but in javascript we can find and resolve these errors in a better way because if we make any program in other languages before program running we need to define variable types for variable and expressions in right manner. But in when we make any program in javascript it considers variable only on running time and it allows some nonsensical things to us without any complaint about example x = true * "monkey" .
But if we write any program in in javascript and this program is not syntactically corrected then errors will come. Apart from that if we call any function in our program and this function is not defined in our program by this an error will be generated in our program and these actions we can say nonsensical action. Because these errors our program is not crash but the output will be incorrect because when we run our program the bogus value comes from several functions because of this the output will be incorrect. The whole process of finding errors or bugs in our program is called debugging. Then there are some error handling techniques in React JS: If there any error is React Js by Javascript then we need to find these errors, logs errors and display a fallback user interface on the webpage instead of the crash all function.
The ErrorBoundary Function
In React JS 16 a new concept, called “error boundary”, is defined for controlling errors without crashing the whole program. Error boundaries are meant to catch all errors during rendering, in lifecycle methods, and in constructors of the whole tree below them: if any errors are found in rendering process then for controlling these errors a new life cycle method componentDidCatch(error, info) is defined with error boundary components. This method is called when an error is generated during rendering process or in any constructor component.
Here's an example of an error boundary class, which implements - as expected - the componentDidCatch method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service logErrorToMyService(error, info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } |
We can use this error boundary class within our code for controlling error like
1 2 3 |
<errorboundary> <mycomponent/> </errorboundary> |
If any error is generated in javascript during rendering process MyComponent throws this error, componentDidCatch catches the error and shows the alert message error occurred! Without crashing MyComponent .
Previously, before React 16, if there any error occurred then it leaves corrupted UI and after loading page, it doesn't work. Apart from that if in React 16 if any error is not controlled by any error boundary the whole application will be un-mounting. For controlling errors we just need to add these error boundaries classes in our app: that way our app will be interacted and protected from these errors instead of crashing.
Useful References
- https://eloquentjavascript.net/08_error.html
- http://www.dotnetcurry.com/reactjs/1353/react-js-tutorial
- http://techbrij.com/react-js-asp-net-mvc-introduction
- https://www.youtube.com/watch?v=6VEdqLGk4xQ