SlideShare a Scribd company logo
1
Adding React Components to
ASP.NET MVC apps with React
JS .NET
Discussion Agenda
• Problem: Modernize (not rebuild) an ASP.NET MVC UI
• Review: React Components
• Big Picture
• How ReactDOM.Render() is called from ASP.NET MVC with
ReactJS.NET
• JSX Files
• Sample Data Exchange
• Rendering Components on the Server Side
• Demo
2
Problem: Modernizing an ASP.NET MVC UI
• ASP.NET MVC websites are not Single Page Applications. Basic components rendered on
the server side (generally speaking), sent to the browser via HTTP Response and JavaScript
functionality is loaded by the browser.
• Industry UI trends favor SPA apps, which are JavaScript-heavy, render quicker and update
more efficiently in response to state changes.
The opinions expressed here are solely those of the author and may not represent
those of many .NET enthusiasts
• The problem is that Modern UI Frameworks (Angular, React, etc) are not compatible with
ASP.NET and require access to a SPA app “Bootstrap” process to load in the browser.
• SPA web apps built with a Modern UI Framework run in JavaScript and ASP.NET MVC apps
run in C#.
• ASP.NET MVC apps can share data, state, etc. with JavaScript classes, but it is not as efficient
as using a framework.
• React JS .NET provides a way to bootstrap a React component tree from a C# view. In
this case, you ASP.NET MVC UI contains a React component tree.
3
Problem: Modernizing an ASP.NET UI
4
• Ng serve
• AppModuleAngular
• ReactDOM
• .render()
React
• HomeController.cs
MVC
JS
loads
app in
browser
Browser loads
ASP.NET MVC
pages sent from
server, Page
load events are
accessed via C#
SPA Web
App
ASP.NET
MVC Web
App
React JS.NET lets us create a React Component
tree when a Razor CSHTML file loads!
Quick Review: React Components
55
• Light but powerful JavaScript library for building
user interfaces.
• Uses components to build UIs.
• React components manage their own internal
state
• Contains library functions for building views
• Components are written in JavaScript and JSX
• Builds views from encapsulated components
so UI only updates necessary elements when
data changes.
• React uses a Virtual DOM to optimize UI
updates.
• All components by implement React render()
function which returns HTML.
• React UI component tree is bootstrapped by
calling ReactDOM.render() in JavaScript
Big Picture – React JS .NET
6
1. React UIs are a tree of components whose root is bootstrapped by calling
the static ReactDOM library method ReactDOM.Render().
2. Using both ASP.NET MVC and React together lets us create a web app
using both MVC Razor UI components rendered on the server and React UI
components rendered in browser.
Ideal especially when modernizing existing ASP.NET sites!
3. We need an efficient way to include the React JavaScript libraries in our
ASP.NET project and call ReactDOM.Render() at the appropriate time in the
Page Lifecycle.
4. React JS.NET lets us share data with the ASP.NET code efficiently by
Get/Post etc. to HTML actions defined in ASP.NET MVC code.
How ReactDOM.Render() is called
7
1. React JS .NET is installed in your ASP.NET MVC project via NuGet. This
contains the React JS core libraries.
2. React JS.NET is initialized via ASP.NET MVC Startup.cs
3. JSX file containing ReactDOM.Render() bootstrap method is referenced in
MVC Razor CSHTML file:
@{
Layout = null;
}
<html>
<head>
<title>Hello React</title>
</head>
<body>
<div id="content"></div>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.development.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-
dom.development.js"></script>
<script src="@Url.Content("~/Scripts/Tutorial.jsx")"></script>
</body>
</html>
Notice that a script tag is used to include
.jsx files!
JSX files: Markup shorthand for React.createElement()
Every React component is created when ReactDOM.Render( ) loads it in the DOM tree.
A React DOM tree of components is created in the browser by calling a tree of React.createElement( )
methods as the tree is traversed.
JSX code compiles from markup to the corresponding React.createElement() upon calling the
implementation of React.render( ) for a component:
8
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)
When defining a React component render( ) method, return JSX markup and the framework will
automatically render the component accordingly!
React.render( )
Making Server Side Data Available from MVC Code
To access data from your MVC app in your React components,
create a Controller Action which returns a list of data in your MVC code:
9
using …
using Microsoft.AspNetCore.Mvc;
using ReactDemo.Models;
namespace ReactDemo.Controllers
{
public class HomeController : Controller
{
private static readonly IList<CommentModel> _comments;
static HomeController()
{
_comments = new List<CommentModel>
{
new CommentModel {Id = 1, Author = "Daniel Lo Nigro",
Text = "Hello ReactJS.NET World!"},
new CommentModel { ….. };
}
public ActionResult Index()
{
return View();
}
}
}
[Route("comments")]
[ResponseCache(Location =
ResponseCacheLocation.None, NoStore = true)]
public ActionResult Comments()
{
return Json(_comments);
}
Create a controller Action in MVC code
which returns a dataset
Fetching Server Side Data from React Code
To fetch data from your MVC code to your React components, add a URL property to the
component pointing to the server side data action. Get it on component mount:
10
class CommentBox extends React.Component {
constructor(props) {
super(props);
this.state = {data: []};
}
componentWillMount() {
const xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = () => {
const data = JSON.parse(xhr.responseText);
this.setState({ data: data });
};
xhr.send();
}
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
}
ReactDOM.render(
<CommentBox url="/comments" />,
document.getElementById('content')
);
Get/Post to the Action from
React code
Rendering Components on the Server Side
For performance needs, you can use React in your Razor CSHTML view code to render
components on the server side.
This will allow for a faster load of the React tree, and is a good way to minimize any performance
dependencies on your MVC code:
11
<!-- This will render the component server-side -->
@Html.React("CommentsBox", new {
initialComments = Model.Comments
})
@Scripts.Render("~/bundles/main")
@Html.ReactInitJavaScript()
// In BundleConfig.cs
bundles.Add(new
JsxBundle("~/bundles/main").Include(
// Add your JSX files here
"~/Scripts/HelloWorld.jsx",
"~/Scripts/AnythingElse.jsx",
"~/Scripts/ajax.js",
));
<!-- In your view -->
@Scripts.Render("~/bundles/main") @Html.React(), @HtmlReactInitJavaScript()
And JsxBundle class are part of React.JS Net
Let’s try it!
Let’s build a quick sample ASP.NET MVC app which contains
a React Hello World Component!
React JS .NET Tutorial:
https://reactjs.net/getting-started/tutorial.html
React JS .NET:
https://reactjs.net/
12

More Related Content

What's hot (20)

PPTX
React JS - Parte 2
Bruno Catão
 
PDF
React Context API
NodeXperts
 
PPTX
Nodejs functions & modules
monikadeshmane
 
PPTX
Introduction to React
Rob Quick
 
PPTX
Herencia encapsulación polimorfismo
Fernando Solis
 
PPTX
React JS: A Secret Preview
valuebound
 
ODP
Basics of VueJS
Squash Apps Pvt Ltd
 
PPTX
Css Basics
Jay Patel
 
PPT
Ppt of Basic MVC Structure
Dipika Wadhvani
 
PDF
introduction to Vue.js 3
ArezooKmn
 
PDF
Introduction to Ruby Programming Language
Nicolò Calcavecchia
 
PPTX
Bootstrap grids
Webtech Learning
 
PPTX
C# REST API
Simplilearn
 
PPTX
Frameworks in java
Darshan Patel
 
ODP
An Introduction to Vuejs
Paddy Lock
 
PPTX
Creating custom Validators on Reactive Forms using Angular 6
AIMDek Technologies
 
PDF
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Loiane Groner
 
PPTX
Web application presentation
Ehsan Ullah Kakar
 
PDF
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
Edureka!
 
PPTX
Its time to React.js
Ritesh Mehrotra
 
React JS - Parte 2
Bruno Catão
 
React Context API
NodeXperts
 
Nodejs functions & modules
monikadeshmane
 
Introduction to React
Rob Quick
 
Herencia encapsulación polimorfismo
Fernando Solis
 
React JS: A Secret Preview
valuebound
 
Basics of VueJS
Squash Apps Pvt Ltd
 
Css Basics
Jay Patel
 
Ppt of Basic MVC Structure
Dipika Wadhvani
 
introduction to Vue.js 3
ArezooKmn
 
Introduction to Ruby Programming Language
Nicolò Calcavecchia
 
Bootstrap grids
Webtech Learning
 
C# REST API
Simplilearn
 
Frameworks in java
Darshan Patel
 
An Introduction to Vuejs
Paddy Lock
 
Creating custom Validators on Reactive Forms using Angular 6
AIMDek Technologies
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Loiane Groner
 
Web application presentation
Ehsan Ullah Kakar
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
Edureka!
 
Its time to React.js
Ritesh Mehrotra
 

Similar to React JS .NET (20)

PDF
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
PDF
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
PPTX
React.js at Cortex
Geoff Harcourt
 
PDF
Tech Talk on ReactJS
Atlogys Technical Consulting
 
PPTX
React js for beginners
Alessandro Valenti
 
PPTX
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
PPTX
React js
Nikhil Karkra
 
PDF
Getting Started with React, When You’re an Angular Developer
Fabrit Global
 
PDF
React js
Rajesh Kolla
 
PPTX
React for .net developers
macsdickinson
 
PDF
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
paridhiagarwal129
 
PPTX
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
PDF
Welcome to React & Flux !
Ritesh Kumar
 
PDF
Review on React JS
ijtsrd
 
PPTX
Rethinking Best Practices
floydophone
 
PDF
Content-Driven Apps with React
Netcetera
 
PDF
React Tech Salon
Chenguang ZHANG
 
PPT
React js
Jai Santhosh
 
PDF
I Heard React Was Good
FITC
 
PPTX
React + Flux = Joy
John Need
 
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
React.js at Cortex
Geoff Harcourt
 
Tech Talk on ReactJS
Atlogys Technical Consulting
 
React js for beginners
Alessandro Valenti
 
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
React js
Nikhil Karkra
 
Getting Started with React, When You’re an Angular Developer
Fabrit Global
 
React js
Rajesh Kolla
 
React for .net developers
macsdickinson
 
theory-slides-vueh3urh4ur4ur4r44oirj4riu4ri
paridhiagarwal129
 
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Welcome to React & Flux !
Ritesh Kumar
 
Review on React JS
ijtsrd
 
Rethinking Best Practices
floydophone
 
Content-Driven Apps with React
Netcetera
 
React Tech Salon
Chenguang ZHANG
 
React js
Jai Santhosh
 
I Heard React Was Good
FITC
 
React + Flux = Joy
John Need
 
Ad

More from Jennifer Estrada (6)

PPTX
Angular View Encapsulation
Jennifer Estrada
 
PPTX
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
PPTX
Angular Data Binding
Jennifer Estrada
 
PPTX
Domain Driven Design for Angular
Jennifer Estrada
 
PPTX
Authenticating Angular Apps with JWT
Jennifer Estrada
 
PPTX
Angular IO
Jennifer Estrada
 
Angular View Encapsulation
Jennifer Estrada
 
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
Angular Data Binding
Jennifer Estrada
 
Domain Driven Design for Angular
Jennifer Estrada
 
Authenticating Angular Apps with JWT
Jennifer Estrada
 
Angular IO
Jennifer Estrada
 
Ad

Recently uploaded (20)

PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Import Data Form Excel to Tally Services
Tally xperts
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Tally software_Introduction_Presentation
AditiBansal54083
 

React JS .NET

  • 1. 1 Adding React Components to ASP.NET MVC apps with React JS .NET
  • 2. Discussion Agenda • Problem: Modernize (not rebuild) an ASP.NET MVC UI • Review: React Components • Big Picture • How ReactDOM.Render() is called from ASP.NET MVC with ReactJS.NET • JSX Files • Sample Data Exchange • Rendering Components on the Server Side • Demo 2
  • 3. Problem: Modernizing an ASP.NET MVC UI • ASP.NET MVC websites are not Single Page Applications. Basic components rendered on the server side (generally speaking), sent to the browser via HTTP Response and JavaScript functionality is loaded by the browser. • Industry UI trends favor SPA apps, which are JavaScript-heavy, render quicker and update more efficiently in response to state changes. The opinions expressed here are solely those of the author and may not represent those of many .NET enthusiasts • The problem is that Modern UI Frameworks (Angular, React, etc) are not compatible with ASP.NET and require access to a SPA app “Bootstrap” process to load in the browser. • SPA web apps built with a Modern UI Framework run in JavaScript and ASP.NET MVC apps run in C#. • ASP.NET MVC apps can share data, state, etc. with JavaScript classes, but it is not as efficient as using a framework. • React JS .NET provides a way to bootstrap a React component tree from a C# view. In this case, you ASP.NET MVC UI contains a React component tree. 3
  • 4. Problem: Modernizing an ASP.NET UI 4 • Ng serve • AppModuleAngular • ReactDOM • .render() React • HomeController.cs MVC JS loads app in browser Browser loads ASP.NET MVC pages sent from server, Page load events are accessed via C# SPA Web App ASP.NET MVC Web App React JS.NET lets us create a React Component tree when a Razor CSHTML file loads!
  • 5. Quick Review: React Components 55 • Light but powerful JavaScript library for building user interfaces. • Uses components to build UIs. • React components manage their own internal state • Contains library functions for building views • Components are written in JavaScript and JSX • Builds views from encapsulated components so UI only updates necessary elements when data changes. • React uses a Virtual DOM to optimize UI updates. • All components by implement React render() function which returns HTML. • React UI component tree is bootstrapped by calling ReactDOM.render() in JavaScript
  • 6. Big Picture – React JS .NET 6 1. React UIs are a tree of components whose root is bootstrapped by calling the static ReactDOM library method ReactDOM.Render(). 2. Using both ASP.NET MVC and React together lets us create a web app using both MVC Razor UI components rendered on the server and React UI components rendered in browser. Ideal especially when modernizing existing ASP.NET sites! 3. We need an efficient way to include the React JavaScript libraries in our ASP.NET project and call ReactDOM.Render() at the appropriate time in the Page Lifecycle. 4. React JS.NET lets us share data with the ASP.NET code efficiently by Get/Post etc. to HTML actions defined in ASP.NET MVC code.
  • 7. How ReactDOM.Render() is called 7 1. React JS .NET is installed in your ASP.NET MVC project via NuGet. This contains the React JS core libraries. 2. React JS.NET is initialized via ASP.NET MVC Startup.cs 3. JSX file containing ReactDOM.Render() bootstrap method is referenced in MVC Razor CSHTML file: @{ Layout = null; } <html> <head> <title>Hello React</title> </head> <body> <div id="content"></div> <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.development.js"></script> <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react- dom.development.js"></script> <script src="@Url.Content("~/Scripts/Tutorial.jsx")"></script> </body> </html> Notice that a script tag is used to include .jsx files!
  • 8. JSX files: Markup shorthand for React.createElement() Every React component is created when ReactDOM.Render( ) loads it in the DOM tree. A React DOM tree of components is created in the browser by calling a tree of React.createElement( ) methods as the tree is traversed. JSX code compiles from markup to the corresponding React.createElement() upon calling the implementation of React.render( ) for a component: 8 <MyButton color="blue" shadowSize={2}> Click Me </MyButton> React.createElement( MyButton, {color: 'blue', shadowSize: 2}, 'Click Me' ) When defining a React component render( ) method, return JSX markup and the framework will automatically render the component accordingly! React.render( )
  • 9. Making Server Side Data Available from MVC Code To access data from your MVC app in your React components, create a Controller Action which returns a list of data in your MVC code: 9 using … using Microsoft.AspNetCore.Mvc; using ReactDemo.Models; namespace ReactDemo.Controllers { public class HomeController : Controller { private static readonly IList<CommentModel> _comments; static HomeController() { _comments = new List<CommentModel> { new CommentModel {Id = 1, Author = "Daniel Lo Nigro", Text = "Hello ReactJS.NET World!"}, new CommentModel { ….. }; } public ActionResult Index() { return View(); } } } [Route("comments")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public ActionResult Comments() { return Json(_comments); } Create a controller Action in MVC code which returns a dataset
  • 10. Fetching Server Side Data from React Code To fetch data from your MVC code to your React components, add a URL property to the component pointing to the server side data action. Get it on component mount: 10 class CommentBox extends React.Component { constructor(props) { super(props); this.state = {data: []}; } componentWillMount() { const xhr = new XMLHttpRequest(); xhr.open('get', this.props.url, true); xhr.onload = () => { const data = JSON.parse(xhr.responseText); this.setState({ data: data }); }; xhr.send(); } render() { return ( <div className="commentBox"> <h1>Comments</h1> <CommentList data={this.state.data} /> <CommentForm /> </div> ); } } ReactDOM.render( <CommentBox url="/comments" />, document.getElementById('content') ); Get/Post to the Action from React code
  • 11. Rendering Components on the Server Side For performance needs, you can use React in your Razor CSHTML view code to render components on the server side. This will allow for a faster load of the React tree, and is a good way to minimize any performance dependencies on your MVC code: 11 <!-- This will render the component server-side --> @Html.React("CommentsBox", new { initialComments = Model.Comments }) @Scripts.Render("~/bundles/main") @Html.ReactInitJavaScript() // In BundleConfig.cs bundles.Add(new JsxBundle("~/bundles/main").Include( // Add your JSX files here "~/Scripts/HelloWorld.jsx", "~/Scripts/AnythingElse.jsx", "~/Scripts/ajax.js", )); <!-- In your view --> @Scripts.Render("~/bundles/main") @Html.React(), @HtmlReactInitJavaScript() And JsxBundle class are part of React.JS Net
  • 12. Let’s try it! Let’s build a quick sample ASP.NET MVC app which contains a React Hello World Component! React JS .NET Tutorial: https://reactjs.net/getting-started/tutorial.html React JS .NET: https://reactjs.net/ 12