SlideShare a Scribd company logo
CS142 Lecture Notes - ReactJS
ReactJS Introduction
Mendel Rosenblum
CS142 Lecture Notes - ReactJS
ReactJS
● JavaScript framework for writing the web applications
○ Like AngularJS - Snappy response from running in browser
○ Less opinionated: only specifies rendering view and handling user interactions
● Uses Model-View-Controller pattern
○ View constructed from Components using pattern
○ Optional, but commonly used HTML templating
● Minimal server-side support dictated
● Focus on supporting for programming in the large and single page applications
○ Modules, reusable components, testing, etc.
CS142 Lecture Notes - ReactJS
ReactJS Web Application Page
<!doctype html>
<html>
<head>
<title>CS142 Example</title>
</head>
<body>
<div id="reactapp"></div>
<script src="./webpackOutput/reactApp.bundle.js"></script>
</body>
</html>
ReactJS applications come as a
JavaScript blob that will use the DOM
interface to write the view into the div.
CS142 Lecture Notes - ReactJS
ReactJS tool chain
Babel - Transpile language features (e.g. ECMAScript, JSX) to basic JavaScript
Webpack - Bundle modules and resources (CSS, images)
Output loadable with single script tag in any browser
Component #1
Component #2
Component #N
...
Babel
Babel
Babel
Webpack
Output
Bundle.js
React.js
React Components
CS142 Lecture Notes - ReactJS
reactApp.js - Render element into browser DOM
import React from 'react';
import ReactDOM from 'react-dom';
import ReactAppView from './components/ReactAppView';
let viewTree = React.createElement(ReactAppView, null);
let where = document.getElementById('reactapp');
ReactDOM.render(viewTree, where);
Renders the tree of React elements (single component
named ReactAppView) into the browser's DOM at the
div with id=reactapp.
ES6 Modules - Bring in
React and web app React
components.
CS142 Lecture Notes - ReactJS
components/ReactAppView.js - ES6 class definition
import React from 'react';
class ReactAppView extends React.Component {
constructor(props) {
super(props);
...
}
render() { ...
};
export default ReactAppView;
Require method render() - returns React
element tree of the Component's view.
Inherits from React.Component. props is
set to the attributes passed to the
component.
CS142 Lecture Notes - ReactJS
ReactAppView render() method
render() {
let label = React.createElement('label', null,'Name: ');
let input = React.createElement('input',
{ type: 'text', value: this.state.yourName,
onChange: (event) => this.handleChange(event) });
let h1 = React.createElement('h1', null,
'Hello ', this.state.yourName, '!');
return React.createElement('div', null, label, input, h1);
}
Returns element tree with div (label, input, and h1) elements
<div>
<label>Name: </label>
<input type="text" … />
<h1>Hello {this.state.yourName}!</h1>
</div>
CS142 Lecture Notes - ReactJS
ReactAppView render() method w/o variables
render() {
return React.createElement('div', null,
React.createElement('label', null,'Name: '),
React.createElement('input',
{ type: 'text', value: this.state.yourName,
onChange: (event) => this.handleChange(event) }),
React.createElement('h1', null,
'Hello ', this.state.yourName, '!')
);
}
CS142 Lecture Notes - ReactJS
Use JSX to generate calls to createElement
render() {
return (
<div>
<label>Name: </label>
<input
type="text"
value={this.state.yourName}
onChange={(event) => this.handleChange(event)}
/>
<h1>Hello {this.state.yourName}!</h1>
</div>
);
}
● JSX makes building tree look like templated HTML embedded in JavaScript.
CS142 Lecture Notes - ReactJS
Component state and input handling
import React from 'react';
class ReactAppView extends React.Component {
constructor(props) {
super(props);
this.state = {yourName: ""};
}
handleChange(event) {
this.setState({ yourName: event.target.value });
}
....
● Input calls to setState which causes React to call render() again
Make <h1>Hello {this.state.yourName}!</h1>
work
CS142 Lecture Notes - ReactJS
One way binding: Type 'D' Character in input box
● JSX statement: <input type="text" value={this.state.yourName}
onChange={(event) => this.handleChange(event)} />
Triggers handleChange call with event.target.value == "D"
● handleChange - this.setState({yourName: event.target.value});
this.state.yourName is changed to "D"
● React sees state change and calls render again:
● Feature of React - highly efficient re-rendering
CS142 Lecture Notes - ReactJS
Calling React Components from events: A problem
class ReactAppView extends React.Component {
...
handleChange(event) {
this.setState({ yourName: event.target.value });
}
...
}
Understand why:
<input type="text" value={this.state.yourName} onChange={this.handleChange} />
Doesn't work!
CS142 Lecture Notes - ReactJS
Calling React Components from events workaround
● Create instance function bound to instance
class ReactAppView extends React.Component {
constructor(props) {
super(props);
this.state = {yourName: ""};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ yourName: event.target.value });
}
CS142 Lecture Notes - ReactJS
Calling React Components from events workaround
● Using public fields of classes with arrow functions
class ReactAppView extends React.Component {
constructor(props) {
super(props);
this.state = {yourName: ""};
}
handleChange = (event) => {
this.setState({ yourName: event.target.value });
}
...
CS142 Lecture Notes - ReactJS
Calling React Components from events workaround
● Using arrow functions in JSX
class ReactAppView extends React.Component {
…
handleChange(event) {
this.setState({ yourName: event.target.value });
}
render() {
return (
<input type="text" value={this.state.yourName}
onChange={(event) => this.handleChange(event)} />
);
}
CS142 Lecture Notes - ReactJS
A digression: camelCase vs dash-case
Word separator in multiword variable name
● Use dashes: active-buffer-entry
● Capitalize first letter of each word: activeBufferEntry
Issue: HTML is case-insensitive but JavaScript is not.
ReactJS's JSX has HTML-like stuff embedded in JavaScript.
ReactJS: Use camelCase for attributes
AngularJS: Used both: dashes in HTML and camelCase in JavaScript!
CS142 Lecture Notes - ReactJS
Programming with JSX
● Need to remember: JSX maps to calls to React.createElement
○ Writing in JavaScript HTML-like syntax that is converted to JavaScript function calls
● React.createElement(type, props, ...children);
○ type: HTML tag (e.g. h1, p) or React.Component
○ props: attributes (e.g. type="text") Uses camelCase!
○ children: Zero or more children which can be either:
■ String or numbers
■ A React element
■ An Array of the above
CS142 Lecture Notes - ReactJS
JSX templates must return a valid children param
● Templates can have JavaScript scope variables and expressions
○ <div>{foo}</div>
■ Valid if foo is in scope (i.e. if foo would have been a valid function call parameter)
○ <div>{foo + 'S' + computeEndingString()}</div>
■ Valid if foo & computeEndString in scope
● Template must evaluate to a value
○ <div>{if (useSpanish) { … } }</div> - Doesn't work: if isn't an expression
○ Same problem with "for loops" and other JavaScript statements that don't return values
● Leads to contorted looking JSX: Example: Anonymous immediate functions
○ <div>{ (function() { if …; for ..; return val;})() }</div>
CS142 Lecture Notes - ReactJS
Conditional render in JSX
● Use JavaScript Ternary operator (?:)
<div>{this.state.useSpanish ? <b>Hola</b> : "Hello"}</div>
● Use JavaScript variables
let greeting;
const en = "Hello"; const sp = <b>Hola</b>;
let {useSpanish} = this.prop;
if (useSpanish) {greeting = sp} else {greeting = en};
<div>{greeting}</div>
CS142 Lecture Notes - ReactJS
Iteration in JSX
● Use JavaScript array variables
let listItems = [];
for (let i = 0; i < data.length; i++) {
listItems.push(<li key={data[i]}>Data Value {data[i]}</li>);
}
return <ul>{listItems}</ul>;
● Functional programming
<ul>{data.map((d) => <li key={d}>Data Value {d}</li>)}</ul>
key= attribute improves efficiency of rendering on data change
CS142 Lecture Notes - ReactJS
Styling with React/JSX - lots of different ways
import React from 'react';
import './ReactAppView.css';
class ReactAppView extends React.Component {
…
render() {
return (
<span className="cs142-code-name">
...
</span>
);
Webpack can import CSS style sheets:
.cs142-code-name {
font-family: Courier New, monospace;
}
Must use className= for HTML
class= attribute (JS keyword
conflict)
CS142 Lecture Notes - ReactJS
Component lifecycle and methods
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
CS142 Lecture Notes - ReactJS
Example of lifecycle methods - update UI every 2s
class Example extends React.Component {
...
componentDidMount() { // Start 2 sec counter
const incFunc =
() => this.setState({ counter: this.state.counter + 1 });
this.timerID = setInterval(incFunc, 2 * 1000);
}
componentWillUnmount() { // Shutdown timer
clearInterval(this.timerID);
}
...
CS142 Lecture Notes - ReactJS
Stateless Components
● React Component can be function (not a class) if it only depends on props
function MyComponent(props) {
return <div>My name is {props.name}</div>;
}
Or using destructuring...
function MyComponent({name}) {
return <div>My name is {name}</div>;
}
● React Hooks (https://reactjs.org/docs/hooks-intro.html)
○ Add state to stateless components - can do pretty much everything the class method can
CS142 Lecture Notes - ReactJS
Example React Hooks
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
CS142 Lecture Notes - ReactJS
Communicating between React components
● Passing information from parent to child: Use props (attributes)
<ChildComponent param={infoForChildComponent} />
● Passing information from child to parent: Callbacks
this.parentCallback = (infoFromChild) =>
{ /* processInfoFromChild */};
<ChildComponent callback={this.parentCallback}> />
● React Context (https://reactjs.org/docs/context.html)
○ Global variables for subtree of components

More Related Content

What's hot

An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
alaa.moustafa
 
Entity Framework Core
Entity Framework CoreEntity Framework Core
Entity Framework Core
Kiran Shahi
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
AnmolPandita7
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
Dzmitry Naskou
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
Sergey Romaneko
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
Tomáš Drenčák
 
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
 
Learn react-js
Learn react-jsLearn react-js
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
Kanda Runapongsa Saikaew
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
PradeepDyavannanavar
 
Intro to React
Intro to ReactIntro to React
Intro to React
Justin Reock
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
Prem Sanil
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
React workshop presentation
React workshop presentationReact workshop presentation
React workshop presentation
Bojan Golubović
 
React js t2 - jsx
React js   t2 - jsxReact js   t2 - jsx
React js t2 - jsx
Jainul Musani
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
Nitin Pande
 

What's hot (20)

An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
 
Entity Framework Core
Entity Framework CoreEntity Framework Core
Entity Framework Core
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
React workshop presentation
React workshop presentationReact workshop presentation
React workshop presentation
 
React js t2 - jsx
React js   t2 - jsxReact js   t2 - jsx
React js t2 - jsx
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 

Similar to ReactJS.pdf

React/Redux
React/ReduxReact/Redux
React/Redux
Durgesh Vaishnav
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
Uldis Sturms
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Learning React: Facebook's Javascript Library For Building User Interfaces
Learning React: Facebook's Javascript Library For Building User InterfacesLearning React: Facebook's Javascript Library For Building User Interfaces
Learning React: Facebook's Javascript Library For Building User Interfaces
Ken Wheeler
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JS
Binary Studio
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
ReactJS
ReactJSReactJS
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React Performance
Ching Ting Wu
 
Using react with meteor
Using react with meteorUsing react with meteor
Using react with meteor
NodeXperts
 
ReactJS.ppt
ReactJS.pptReactJS.ppt
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
Nitin Tyagi
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
[T]echdencias
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
Evan Schultz
 
React native
React nativeReact native
React native
Vishal Dubey
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
RAJNISH KATHAROTIYA
 
Combining Angular and React Together
Combining Angular and React TogetherCombining Angular and React Together
Combining Angular and React Together
Sebastian Pederiva
 
Universal JS Applications with React
Universal JS Applications with ReactUniversal JS Applications with React
Universal JS Applications with React
Thanh Trần Trọng
 
React outbox
React outboxReact outbox
React outbox
Angela Lehru
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
vhazrati
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
Xebia IT Architects
 

Similar to ReactJS.pdf (20)

React/Redux
React/ReduxReact/Redux
React/Redux
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Learning React: Facebook's Javascript Library For Building User Interfaces
Learning React: Facebook's Javascript Library For Building User InterfacesLearning React: Facebook's Javascript Library For Building User Interfaces
Learning React: Facebook's Javascript Library For Building User Interfaces
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JS
 
React lecture
React lectureReact lecture
React lecture
 
ReactJS
ReactJSReactJS
ReactJS
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React Performance
 
Using react with meteor
Using react with meteorUsing react with meteor
Using react with meteor
 
ReactJS.ppt
ReactJS.pptReactJS.ppt
ReactJS.ppt
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
 
React native
React nativeReact native
React native
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
Combining Angular and React Together
Combining Angular and React TogetherCombining Angular and React Together
Combining Angular and React Together
 
Universal JS Applications with React
Universal JS Applications with ReactUniversal JS Applications with React
Universal JS Applications with React
 
React outbox
React outboxReact outbox
React outbox
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 

Recently uploaded

Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 

Recently uploaded (20)

Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 

ReactJS.pdf

  • 1. CS142 Lecture Notes - ReactJS ReactJS Introduction Mendel Rosenblum
  • 2. CS142 Lecture Notes - ReactJS ReactJS ● JavaScript framework for writing the web applications ○ Like AngularJS - Snappy response from running in browser ○ Less opinionated: only specifies rendering view and handling user interactions ● Uses Model-View-Controller pattern ○ View constructed from Components using pattern ○ Optional, but commonly used HTML templating ● Minimal server-side support dictated ● Focus on supporting for programming in the large and single page applications ○ Modules, reusable components, testing, etc.
  • 3. CS142 Lecture Notes - ReactJS ReactJS Web Application Page <!doctype html> <html> <head> <title>CS142 Example</title> </head> <body> <div id="reactapp"></div> <script src="./webpackOutput/reactApp.bundle.js"></script> </body> </html> ReactJS applications come as a JavaScript blob that will use the DOM interface to write the view into the div.
  • 4. CS142 Lecture Notes - ReactJS ReactJS tool chain Babel - Transpile language features (e.g. ECMAScript, JSX) to basic JavaScript Webpack - Bundle modules and resources (CSS, images) Output loadable with single script tag in any browser Component #1 Component #2 Component #N ... Babel Babel Babel Webpack Output Bundle.js React.js React Components
  • 5. CS142 Lecture Notes - ReactJS reactApp.js - Render element into browser DOM import React from 'react'; import ReactDOM from 'react-dom'; import ReactAppView from './components/ReactAppView'; let viewTree = React.createElement(ReactAppView, null); let where = document.getElementById('reactapp'); ReactDOM.render(viewTree, where); Renders the tree of React elements (single component named ReactAppView) into the browser's DOM at the div with id=reactapp. ES6 Modules - Bring in React and web app React components.
  • 6. CS142 Lecture Notes - ReactJS components/ReactAppView.js - ES6 class definition import React from 'react'; class ReactAppView extends React.Component { constructor(props) { super(props); ... } render() { ... }; export default ReactAppView; Require method render() - returns React element tree of the Component's view. Inherits from React.Component. props is set to the attributes passed to the component.
  • 7. CS142 Lecture Notes - ReactJS ReactAppView render() method render() { let label = React.createElement('label', null,'Name: '); let input = React.createElement('input', { type: 'text', value: this.state.yourName, onChange: (event) => this.handleChange(event) }); let h1 = React.createElement('h1', null, 'Hello ', this.state.yourName, '!'); return React.createElement('div', null, label, input, h1); } Returns element tree with div (label, input, and h1) elements <div> <label>Name: </label> <input type="text" … /> <h1>Hello {this.state.yourName}!</h1> </div>
  • 8. CS142 Lecture Notes - ReactJS ReactAppView render() method w/o variables render() { return React.createElement('div', null, React.createElement('label', null,'Name: '), React.createElement('input', { type: 'text', value: this.state.yourName, onChange: (event) => this.handleChange(event) }), React.createElement('h1', null, 'Hello ', this.state.yourName, '!') ); }
  • 9. CS142 Lecture Notes - ReactJS Use JSX to generate calls to createElement render() { return ( <div> <label>Name: </label> <input type="text" value={this.state.yourName} onChange={(event) => this.handleChange(event)} /> <h1>Hello {this.state.yourName}!</h1> </div> ); } ● JSX makes building tree look like templated HTML embedded in JavaScript.
  • 10. CS142 Lecture Notes - ReactJS Component state and input handling import React from 'react'; class ReactAppView extends React.Component { constructor(props) { super(props); this.state = {yourName: ""}; } handleChange(event) { this.setState({ yourName: event.target.value }); } .... ● Input calls to setState which causes React to call render() again Make <h1>Hello {this.state.yourName}!</h1> work
  • 11. CS142 Lecture Notes - ReactJS One way binding: Type 'D' Character in input box ● JSX statement: <input type="text" value={this.state.yourName} onChange={(event) => this.handleChange(event)} /> Triggers handleChange call with event.target.value == "D" ● handleChange - this.setState({yourName: event.target.value}); this.state.yourName is changed to "D" ● React sees state change and calls render again: ● Feature of React - highly efficient re-rendering
  • 12. CS142 Lecture Notes - ReactJS Calling React Components from events: A problem class ReactAppView extends React.Component { ... handleChange(event) { this.setState({ yourName: event.target.value }); } ... } Understand why: <input type="text" value={this.state.yourName} onChange={this.handleChange} /> Doesn't work!
  • 13. CS142 Lecture Notes - ReactJS Calling React Components from events workaround ● Create instance function bound to instance class ReactAppView extends React.Component { constructor(props) { super(props); this.state = {yourName: ""}; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ yourName: event.target.value }); }
  • 14. CS142 Lecture Notes - ReactJS Calling React Components from events workaround ● Using public fields of classes with arrow functions class ReactAppView extends React.Component { constructor(props) { super(props); this.state = {yourName: ""}; } handleChange = (event) => { this.setState({ yourName: event.target.value }); } ...
  • 15. CS142 Lecture Notes - ReactJS Calling React Components from events workaround ● Using arrow functions in JSX class ReactAppView extends React.Component { … handleChange(event) { this.setState({ yourName: event.target.value }); } render() { return ( <input type="text" value={this.state.yourName} onChange={(event) => this.handleChange(event)} /> ); }
  • 16. CS142 Lecture Notes - ReactJS A digression: camelCase vs dash-case Word separator in multiword variable name ● Use dashes: active-buffer-entry ● Capitalize first letter of each word: activeBufferEntry Issue: HTML is case-insensitive but JavaScript is not. ReactJS's JSX has HTML-like stuff embedded in JavaScript. ReactJS: Use camelCase for attributes AngularJS: Used both: dashes in HTML and camelCase in JavaScript!
  • 17. CS142 Lecture Notes - ReactJS Programming with JSX ● Need to remember: JSX maps to calls to React.createElement ○ Writing in JavaScript HTML-like syntax that is converted to JavaScript function calls ● React.createElement(type, props, ...children); ○ type: HTML tag (e.g. h1, p) or React.Component ○ props: attributes (e.g. type="text") Uses camelCase! ○ children: Zero or more children which can be either: ■ String or numbers ■ A React element ■ An Array of the above
  • 18. CS142 Lecture Notes - ReactJS JSX templates must return a valid children param ● Templates can have JavaScript scope variables and expressions ○ <div>{foo}</div> ■ Valid if foo is in scope (i.e. if foo would have been a valid function call parameter) ○ <div>{foo + 'S' + computeEndingString()}</div> ■ Valid if foo & computeEndString in scope ● Template must evaluate to a value ○ <div>{if (useSpanish) { … } }</div> - Doesn't work: if isn't an expression ○ Same problem with "for loops" and other JavaScript statements that don't return values ● Leads to contorted looking JSX: Example: Anonymous immediate functions ○ <div>{ (function() { if …; for ..; return val;})() }</div>
  • 19. CS142 Lecture Notes - ReactJS Conditional render in JSX ● Use JavaScript Ternary operator (?:) <div>{this.state.useSpanish ? <b>Hola</b> : "Hello"}</div> ● Use JavaScript variables let greeting; const en = "Hello"; const sp = <b>Hola</b>; let {useSpanish} = this.prop; if (useSpanish) {greeting = sp} else {greeting = en}; <div>{greeting}</div>
  • 20. CS142 Lecture Notes - ReactJS Iteration in JSX ● Use JavaScript array variables let listItems = []; for (let i = 0; i < data.length; i++) { listItems.push(<li key={data[i]}>Data Value {data[i]}</li>); } return <ul>{listItems}</ul>; ● Functional programming <ul>{data.map((d) => <li key={d}>Data Value {d}</li>)}</ul> key= attribute improves efficiency of rendering on data change
  • 21. CS142 Lecture Notes - ReactJS Styling with React/JSX - lots of different ways import React from 'react'; import './ReactAppView.css'; class ReactAppView extends React.Component { … render() { return ( <span className="cs142-code-name"> ... </span> ); Webpack can import CSS style sheets: .cs142-code-name { font-family: Courier New, monospace; } Must use className= for HTML class= attribute (JS keyword conflict)
  • 22. CS142 Lecture Notes - ReactJS Component lifecycle and methods http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
  • 23. CS142 Lecture Notes - ReactJS Example of lifecycle methods - update UI every 2s class Example extends React.Component { ... componentDidMount() { // Start 2 sec counter const incFunc = () => this.setState({ counter: this.state.counter + 1 }); this.timerID = setInterval(incFunc, 2 * 1000); } componentWillUnmount() { // Shutdown timer clearInterval(this.timerID); } ...
  • 24. CS142 Lecture Notes - ReactJS Stateless Components ● React Component can be function (not a class) if it only depends on props function MyComponent(props) { return <div>My name is {props.name}</div>; } Or using destructuring... function MyComponent({name}) { return <div>My name is {name}</div>; } ● React Hooks (https://reactjs.org/docs/hooks-intro.html) ○ Add state to stateless components - can do pretty much everything the class method can
  • 25. CS142 Lecture Notes - ReactJS Example React Hooks import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
  • 26. CS142 Lecture Notes - ReactJS Communicating between React components ● Passing information from parent to child: Use props (attributes) <ChildComponent param={infoForChildComponent} /> ● Passing information from child to parent: Callbacks this.parentCallback = (infoFromChild) => { /* processInfoFromChild */}; <ChildComponent callback={this.parentCallback}> /> ● React Context (https://reactjs.org/docs/context.html) ○ Global variables for subtree of components