Using ReactJS component in Asp.Net MVC
React JS is one of the recent JS frameworks used to develop component based UI architecture. There are many application already developed in Asp.Net MVC or Asp.Net MVC Core. We use Razor framework not only to design the complete HTML of UI pages but also the templates to be reused for various purposes.
However, reusing the templates many times result into a limitation if it is aimed for a component especially, when we want to customize the behaviour of such components. In such cases, we can create a ReactJS components as described below to control the customization for each instance of the component.
Below are the list of Software to be installed prior to applying the example given in this blog.
- Visual Studio 2017
- Asp.Net Core 1.1 with C#.Net
- ReactJs.Net extension in VS 2017 (Refer the details here).
As a prerequisite, knowledge of the ReactJS and Asp.Net Core is essential.
This is an example of developing a reusable TextBox component which can be used either as a normal textbox or as a password enabled textbox.
- This component displays a Label along with a TextBox control.
- The Html structure of this component can be customized as needed.
- There are 5 props defined for this component:
- password = If true, the Html input textbox type will be password else it will be textbox.
- label = A text displayed as a label before the control.
- id = A unique Id of an Html input textbox.
- text = A value to be displayed in an Html input textbox.
- placeholder = A value to be displayed when textbox is empty.
- cssClass = as the name indicates, it’s a CSS class to be applied to an Html input textbox.
Integration in Razor View
Above component can be integrated in the Razor View (cshtml) as shown below.
- First instance of TextBox component is a normal Html input textbox with given values of the props. This is indicated by setting the password props as false.
- Second instance is a Password enabled Html input textbox by setting the password pros as true.
We can fit the instance of Textbox component in any UI structure of the Razor view, as needed.