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

React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
valuebound
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
Ritesh Mehrotra
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
ReactJs
ReactJsReactJs
React render props
React render propsReact render props
React render props
Saikat Samanta
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
ReactJS
ReactJSReactJS
learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .
paradisetechsoftsolutions
 
React-js
React-jsReact-js
React-js
Avi Kedar
 
React js
React jsReact js
React js
Alireza Akbari
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View Encapsulation
Jennifer Estrada
 
Intro to React
Intro to ReactIntro to React
Intro to React
Eric Westfall
 
Introduction to ReactJs & fundamentals
Introduction to ReactJs & fundamentalsIntroduction to ReactJs & fundamentals
Introduction to ReactJs & fundamentals
websyndicate
 
Intro to React
Intro to ReactIntro to React
Intro to React
Justin Reock
 
React js
React jsReact js
React js
Nikhil Karkra
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
Rob Quick
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
Knoldus Inc.
 
React js Rahil Memon
React js Rahil MemonReact js Rahil Memon
React js Rahil Memon
RahilMemon5
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
Divyang Bhambhani
 

What's hot (20)

React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 
Reactjs
Reactjs Reactjs
Reactjs
 
ReactJs
ReactJsReactJs
ReactJs
 
React render props
React render propsReact render props
React render props
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
ReactJS
ReactJSReactJS
ReactJS
 
learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .
 
React-js
React-jsReact-js
React-js
 
React js
React jsReact js
React js
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View Encapsulation
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Introduction to ReactJs & fundamentals
Introduction to ReactJs & fundamentalsIntroduction to ReactJs & fundamentals
Introduction to ReactJs & fundamentals
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React js
React jsReact js
React js
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
React js Rahil Memon
React js Rahil MemonReact js Rahil Memon
React js Rahil Memon
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 

Similar to React JS .NET

GDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJSGDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJS
Pratik Majumdar
 
BackboneJS + ReactJS
BackboneJS + ReactJSBackboneJS + ReactJS
BackboneJS + ReactJS
Skanda Shastry
 
Reactjs notes.pptx for web development- tutorial and theory
Reactjs  notes.pptx for web development- tutorial and theoryReactjs  notes.pptx for web development- tutorial and theory
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
Nitin Tyagi
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
Rasel Khan
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react js
BOSC Tech Labs
 
Reactjs
ReactjsReactjs
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
Taranjeet Singh
 
React, Flux and more (p1)
React, Flux and more (p1)React, Flux and more (p1)
React, Flux and more (p1)
tuanpa206
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
Bethmi Gunasekara
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
Hùng Nguyễn Huy
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
DayNightGaMiNg
 
slides.pptx
slides.pptxslides.pptx
slides.pptx
HafidzIhzaPratama
 

Similar to React JS .NET (20)

GDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJSGDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJS
 
Intro react js
Intro react jsIntro react js
Intro react js
 
BackboneJS + ReactJS
BackboneJS + ReactJSBackboneJS + ReactJS
BackboneJS + ReactJS
 
Reactjs notes.pptx for web development- tutorial and theory
Reactjs  notes.pptx for web development- tutorial and theoryReactjs  notes.pptx for web development- tutorial and theory
Reactjs notes.pptx for web development- tutorial and theory
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react js
 
Reactjs
ReactjsReactjs
Reactjs
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
React, Flux and more (p1)
React, Flux and more (p1)React, Flux and more (p1)
React, Flux and more (p1)
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
slides.pptx
slides.pptxslides.pptx
slides.pptx
 
slides.pptx
slides.pptxslides.pptx
slides.pptx
 

Recently uploaded

Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 

Recently uploaded (20)

Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 

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