Warm up
Answer short questions and introduce yourself
Quiz 1
JS is a strongly typed language
A. Yes B. No
[Link]
Quiz 2
You can only run JS in browser
A. Yes B. No
Quiz 3
You can assign a function to a variable
A. Yes B. No
Quiz 4
A variable in a function always dies after the
execution of the function
A. Yes B. No
[Link]
Quiz 5
jQuery is a framework
A. Yes B. No
Course introduction
Through this course, you’ll gain knowledge regarding:
● What is React and why React
● Writing stateless React components
● Writing stateful React components
● React events handling
● React forms handling
● Asynchronous programming in React
● Writing SPA using React
● Advanced tips and techniques
● Production and deployment
React
Getting started
Is it worth learning?
Who use React
Facebook (of course)
Instagram
Netflix
WhatsApp
Dropbox
Job Market!
Topics for today
● What is React
● ReactDOM and JSX
● DOM and Virtual DOM
● React functional components
● React props
● ES6 basics
What is React
“A declarative, efficient, and flexible JavaScript
library for building user interfaces” - facebook
[Link]
Hello React
[Link](
<h1>Hello, react!</h1>,
[Link]('root')
);
Yes, it is simple as this!
Render a form using React
[Link](
<form>
<input name="username" type="text" />
<input name="password" type="password" />
<button type="submit">Sign in</button>
</form>,
[Link]('root')
)
Lab
● Use create-react-app to create your first react app
[Link]
ReactDOM
[Link] takes 2 parameters:
! JSX (what you want to render)
! Mount node (where you want to render)
What is JSX
JSX = JavaScript XML
const element = <h1>Hello, world!</h1>;
A syntax extension to JavaScript, which produces React elements
Can be complex. Note, technically it is not HTML.
const loginForm = (
<form>
<input name="username" type="text" />
<input name="password" type="password" />
<button type="submit">Sign in</button>
</form>
);
If you can write a bit HTML, then you can write React already!
React magic
[Link](JSX) = HTML in
browser!
JSX caveats
Use CSS class: <button className="btn btn-primary">Next</button>
Use style: <span style={{ fontStyle: "italic" }}>Message</span>
Close tags:
<input className="form-control"> - WRONG
<input className="form-control" /> - CORRECT
DOM and Virtual DOM
DOM
DOM stands for Document Object Model.
“With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.” - w3schools
DOM programming example
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
However...
DOM was never optimized for creating dynamic UI
DOM programming is imperative
— declarative vs imperative programming:
[Link]
React Virtual DOM
This is a lightweight DOM from JavaScript objects that mimic a real DOM. React
builds and maintains a virtual DOM internally. Whenever it needs to render UI, it
constructs the virtual DOM first, which is lightning fast process.
Then, it compares the virtual DOM to the real DOM, computing the DOM
difference. Using the difference, React knows how to update the DOM in a very
efficient way (rather than refreshing the whole UI).
JSX and Virtual DOM
React uses JSX to build virtual DOM, where React elements live. Then use
ReactDOM to render all the React elements into browser, which results in a real
DOM.
Lab time: display current time
Use [Link] + JSX (shown as below) and setInterval to build a clock,
which displays current time
<div>
<h1>It is {new Date().toLocaleTimeString()} now.</h1>
</div>
React functional components
React components
A React component is React element, and is made of one or multiple React
elements. There are three types of React components.
! Functional components (stateless)
! Class components (stateful, we’ll see this in next session)
! Pure components
Functional components are… functions
function Welcome() {
return <h1>Hello, my friend!</h1>;
}
[Link](
<div>
<Welcome />
</div>,
[Link](‘root’)
);
Functional components with props
A static component is almost useless. Let’s make our component a bit more
dynamic. In theory, you could pass unlimited number of attributes to Welcome
component.
function Welcome(props) {
return <h1>Hello, {[Link]}!</h1>;
}
[Link](
<div>
<Welcome name="Brad Pitt" />
</div>,
[Link](‘root’)
);
More functional components
function StudentCard(props) {
return (
<div>
<h1>{[Link]}</h1>
<div>Age: {[Link]}</div>
</div>
);
}
[Link](
<div>
<StudentCard name="Jane" age={15} />
<StudentCard name="John" age={17} />
<StudentCard name="Ben" age={21} />
</div>,
[Link]('root'));
Assign values to props
A valid value for props is JavaScript expression, and it looks like this in JSX:
<MyComponent foo={JavaScript expression} />
JavaScript expressions include but not limited to:
! Number - <Component number={12} />
! String - <Component str="Hello world" />
! Boolean - <Component liked={false} /> <Component liked />
! Array - <Component array={[1, 2, 3, 4]} />
! Object - <Component style={{ fontWeight: 'bold' }} />
! Operators - <Component sum={1 + 2 + 3} />
! Function - <Component onClick={() => alert('clicked')} />
Props are immutable
All React components must act like pure functions with respect to their props.
function StudentCard(props) {
[Link] = 22; // This doesn't work
return (
<div>
<h1>{[Link]}</h1>
<div>Age: {[Link]}</div>
</div>
);
}
[Link](<StudentCard name="Jane" age={15} />, [Link]('root'));
Pure and impure
Pure - doesn’t change the input (i.e. a and b)
function sum(a, b) {
return a + b;
}
Impure - input (account) is mutated
function withdraw(account, amount) {
[Link] -= amount;
}
Generally, pure functions are preferred, as they surprise people less.
Pure components
- High performance
- Similar to stateful components
- State & lifecycle methods access
[Link]
d2af88a1200b
ES6 Basics
What is ES6 (aka ES2015)
ECMAScript 6 (ES6) is the upcoming sixth major release of the ECMAScript language specification.
ECMAScript is the “proper” name for the language commonly referred to as JavaScript.
Can we use ES6 today?
[Link]
What if target browsers do not support ES6 => Use transpiler
Let’s be brutal here:
If you want to use React, you HAVE TO learn ES6
ES6 - const
const makes your variable immutable
const pi = 3.1415926;
pi = 4; // doesn't work, error thrown
ES6 - template string
Use `` and ${...} to interpolate variables
function displayStudentInfo(student) {
return `${[Link]} is ${[Link]} years old`.
}
Use `` for multiple lines
const multipleLines = `
Hi,
It's me again.
Long time no see!
`;
ES6 - let
for (var i = 0; i < 3; i++) {
[Link](i);
}
[Link](i); // outputs 3!
i still exists after the execution and its value is 3
for (let j = 0; j < 3; j++) {
[Link](j);
}
[Link](j); // not defined error
j is destroyed after the execution
ES6 - arrow function
function sayHello(name) {
[Link](`hello, ${name}!`);
}
const sayHello = (name) => {
[Link](`hello, ${name}!`);
}
ES6 - destructuring
const student = { name: 'Jane', age: 15, gender: 'F' };
const name = [Link];
const age = [Link];
const gender = [Link];
const { name, age, gender } = student;
Take some time to get used to this. We use destructuring everyday in our
programming life.
ES6 - spread
const computerScienceStudent = {
major: 'Computer Science',
language: 'English',
university: 'UNSW'
};
const mary = {
...computerScienceStudent,
language: 'Chinese',
age: 25
};
/*
mary = { major: 'Computer Science', language: 'Chinese',
university = 'UNSW', age: 25 }
*/
ES6 - class
class Student {
constructor(name) {
[Link] = name;
[Link] = 'UNSW';
}
greeting() {
[Link](`Hello, I'm ${[Link]} from {[Link]}`);
}
}
const jane = new Student('Jane');
[Link](); // Hello, I’m Jane from UNSW
Homework 1
Implement this component using React functional component
Your component should work like this:
<Card img="..." title="..." subTitle="..." />
Homework 2: reading time
Virtual DOM: [Link]
DOM and Virtual DOM: [Link]
virtual-dom-and-dom
ES6: [Link]
a2ed0b5c977e
Recap
● What is React
● ReactDOM and JSX
● DOM and Virtual DOM
● React functional components
● React props
● ES6 basics