Lecture # 12 - Introduction To React JS
Lecture # 12 - Introduction To React JS
Lecture # 12 - Introduction To React JS
Advanced Programming
1
What is React?
Open Source JavaScript Library for building user
interfaces
Not a Framework
Focus on UI
• (not have to worry about other aspects like HTTP request
handling etc.)
• Rich ecosystem(can be placed with other libraries and is
more than capable of building a full fledge web
application)
2
Why learn React?
Created and maintained by Facebook
More than 100k stars on GitHub
Huge Community
In demand skillset
3
Component Base Architecture
Break down your application into small encapsulated parts
and then can be composed to make more complex UIs
Header
SideNa
MAIN CONTENT
v
Footer
4
Reusable Code
Same component can be used with different data.
Angular React Vue
Article Article
Article
Component Component
Component
5
React is declarative
Tell React what you want and React will build the actual
UI
React DOM library ‘ll build it
Declarative Paradigm VS Imperative Paradigm?
Draw a landscape ?
React will handle efficiently updating and rendering of the
components
DOM updates are handled gracefully in React
6
More on why React?
Seamlessly integrate react into any of your application
Portion of your page or a complete page or even an entire
application itself.
React is used to build single page applications. Facebook,
Twitter etc
React Native for Mobile Applications
Great Addition to your skillset
7
Prerequisites
HTML, CSS and JavaScript fundamentals
ES6(ECMAScript)
Knowledge of modern Javascript
No need to be expert in ES6 but need to know some new
features
React uses ES6, and you should be familiar with some of
the new features like: This Key word
I. Classes
II. Arrow Functions
III. Variables (let, const, var)
8
What is ES6?
ES6 stands for ECMAScript 6.
ECMAScript was created to standardize JavaScript, and ES6 is the 6th
version of ECMAScript, it was published in 2015, and is also known as
ECMAScript 2015.
ES6 introduced classes.
A class is a type of function, but instead of using the keyword function to
initiate it, we use the keyword class
class Car {
constructor(name) {
this.brand = name;
}
}
mycar = new Car("Ford");
9
ES6……Methods in class
You can add your own methods in a class:
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}
}
10
ES6…Class Inheritance
To create a class inheritance, use the extends keyword.
class Car {
constructor(name) {
this.brand = name; }
present() {
return 'I have a ' + this.brand; }}
class Model extends Car {
constructor(name, mod) {
super(name);
this.model = mod; }
show() {
return this.present() + ', it is a ' + this.model}}
mycar = new Model("Ford", "Mustang");
mycar.show();
The super() method refers to the parent class.
11
Es6.. Arrow Functions
Arrow functions were introduced in ES6.
Arrow functions allow us to write shorter function syntax:
hello = function() {
return "Hello World!";
}
VS
hello = () => {
return "Hello World!";
}
If the function has only one statement, remove {}
12
ES6.. Arrow Functions with parameters
hello = (val) => "Hello " + val;
if you have only one parameter, you can skip the
parentheses as well:
hello = val => "Hello " + val;
Before ES6 A variable was defined the var keyword
Now, with ES6, there are three ways of defining your
variables: var, let, and const.
13
How Does React Work?
React creates a VIRTUAL DOM in memory.
Instead of manipulating the browser's DOM directly,
React creates a virtual DOM in memory, where it does all
the necessary manipulating, before making the changes in
the browser DOM.
React only changes what needs to be changed!
14
React – Hello World Application
Two Things are required
Node & Text Editor of your choice
The create-react-app is an officially supported way to create React applications.
Install create-react-app by running this command in your terminal:
C:\Users\Your Name>npm install -g create-react-app
You are now ready to create your first React application!
C:\Users\Your Name>npx create-react-app my-app
npx is npm package runner
The create-react-app will set up everything you need to run a React application.
Open App.js
Now Run command C:\Users\Your Name>npm start
15
Folder Structure
16
Important Files Description
Package.json : Dependencies and scripts required for the
project
Nodes_modules : All dependencies are installed in it
Public/index.html is the page template
src/index.js is the JavaScript entry point for react
application. Root Element and DOM component
controlled by React is specified in it.
src/App.js : Responsible for HTML displayed in browser
17
Components
Represents a part of User Interface
Components are building blocks of any react application
Root Component (Usually with name App) contains other
components
Components are reusable with different data
Components can be nested inside other components
They serve the same purpose as JavaScript functions, but
work in isolation and returns HTML via a render function.
18
Component in code
19
Components…
Can have both .js extention and JSX
How Code look like for a component?
Depends on the Type of the Component
Functional Component
Class Component
function Welcome(props){
return <h1>Hello,
{props.name}</h1>
}
20
Components…
Class extending component class from React Library
Render Method Returning HTML Class
22
Functional….
Create Greet Component (Greet.js) as below
23
Functional……
import React from 'react';
import logo from './logo.svg';
import './App.css'; Import
import Greet from '/Greet‘ component
class App extends Component(){
render(){
return (
<div className="App"> Use like a
<Greet></Greet> custom Tag
</div> );
}
export default App;
- Now Run it and see Hello User on browser
24
Functional….
Same Functional Component with Arrow Function
import React from 'react';
const Greet =()=><h1>Hello User</h1>
Export Default ?
import Greet from '/Greet‘ …Component name can be of
your choice with default export and use that tag..
import MyComponent from '/Greet‘
<MyComponent> </MyComponent>
Named export?
export const Greet =()=><h1>Hello User</h1>\
import {Greet} from '/Greet‘
25
Class Components
26
Class Component..
import React,{Component} from 'react';
class Greet extends Component {
render(){
retrun <h1>Hello User</h1>
}
}
export default Greet;
-- Import in App.js and add custom Tag
<Greet></Greet>
27
JSX
JSX stands for JavaScript XML.
Extension to the Javascript language Syntax
Write XML like code for elements and components
XML Tags have tag name, attributes and children
JSX is not a necessity to write React Application
JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in React,
makes code simpler and elegant
JSX ultimately transpiles to pure JS which is understood
by browser.
28
Component With/Without JSX
import React from 'react';
const Hello =()=>
{
return(
<div className=‘dummyClass’>
<h1>Hello User</h1>
</div>)
}
export default Hello;
29
JSX…..
return React.CreateElement (at min 3 params)
Tag to be rendered, optional params(name, id, class etc),
children for the html element.
import React from 'react';
const Hello =()=>
{
return React.CreateElement(‘div’,null,’Hello User’)
}
export default Hello;
30
JSX….
return React.CreateElement(‘div’,null,’Hello User’)
return React.CreateElement(‘div’,null,React.CreateElement
(‘h1’,null,’Hello User’)
return React.CreateElement(‘div’,{id:’hello’,className:
‘dummyClass’},React.CreateElement (‘h1’,null,’Hello User’)
31
JSX….
import React from 'react';
const Greet =()=><h1>Hello User</h1>
export default Greet;
Why need to import React when we did not use anywhere in
code?
JSX translates into React.CreateElement which in turn uses
react library.
Imagine 100 of components…
JSX keeps code simple, elegant and readable.
32
Differences of JSX with regular HTML
class className
for htmlFor
camelCase property naming convention
onclick onClick
33
Props
Props are arguments passed into React components.
Props are passed to components via HTML attributes .
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from '/Greet‘
class App extends Component(){
render(){
return (
<div className="App">
<Greet></Greet>
<Greet></Greet> component can be used as many time
<Greet></Greet>
</div> );
}
export default App;
34
Props….
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from '/Greet‘
class App extends Component(){
render(){
return (
<div className="App">
<Greet name=“Aslam”/>
<Greet name=“Akram”/>
<Greet name=“Muhammad”/>
</div> );
}
export default App;
35
Props…..
import React from 'react';
const Greet =(props)=>{
return <h1>Hello props.name</h1>
}
export default Greet;
36
Props….
import React from 'react';
const Greet =(props)=>{
return <h1>Hello {props.name}</h1>
}
export default Greet;
{} is a feature of JSX
Open and check in
Hello Aslam
Hello Akram
Hello Muhammad
37
Props….
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from '/Greet‘
class App extends Component(){
render(){
return (
<div className="App">
<Greet name=“Aslam” heroName=“Batman”/>
<Greet name=“Akram” heroName=“Superman” />
<Greet name=“Muhammad” heroName=“Champion” />
</div> );
}
export default App;
38
Props…
import React from 'react';
const Greet =(props)=>{
return <h1>Hello {props.name} a.k.a
{props.heroName}</h1>
}
export default Greet;
Hello Aslam a.k.a Batman
Hello Akram a.k.a Superman
Hello Muhammad a.k.a Champion
39
Props….
Show unknown component through reserved children property of props.
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from '/Greet‘
class App extends Component(){
render(){
return (
<div className="App">
<Greet name=“Aslam” heroName=“Batman”>
<p> this is children props</p>
</Greet>
<Greet name=“Akram” heroName=“Superman” />
<Greet name=“Muhammad” heroName=“Champion” />
</div> );
}
export default App;
40
Props…
import React from 'react';
const Greet =(props)=>{
return (
<h1>Hello {props.name} a.k.a {props.heroName}</h1>
{props.children}
)
}
*This will give error.. In JSX return can contain one
wrapper element..
41
Props….
import React from 'react';
const Greet =(props)=>{
return (
<div>
<h1>Hello {props.name} a.k.a {props.heroName}</h1>
{props.children}
</div>
)
}
Wrap in <div> tag….
42
Props….
43
Props…
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from '/Greet‘
class App extends Component(){
render(){
return (
<div className="App">
<Greet name=“Aslam” heroName=“Batman”>
<p> this is children props</p>
</Greet>
<Greet name=“Akram” heroName=“Superman” >
<button>Action</button>
</Greet>
<Greet name=“Muhammad” heroName=“Champion” />
</div> );
}
export default App;
44
Class Definition…Recall
import React,{Component} from 'react';
class Greet extends Component {
render(){
retrun <h1>Hello User</h1>
}
}
export default Greet;
45
Props… with class component
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Greet from '/Greet‘
class App extends Component(){
render(){
return (
<div className="App">
<Greet name=“Aslam” heroName=“Batman”/>
<Greet name=“Akram” heroName=“Superman” />
<Greet name=“Muhammad” heroName=“Champion” />
</div> );
}
export default App;
46
Props…. With class component
import React,{Component} from 'react';
class Greet extends Component {
render(){
retrun <h1>Hello {this.props.name} a.k.s
{this.props.heroName} </h1>
}
}
export default Greet;
Hello Aslam a.k.a Batman
Hello Akram a.k.a Superman
Hello Muhammad a.k.a Champion
47
Props….
Props are immutable(can not be changed)
Try below code and check output
49
State
Props vs state
Props gets passed to the component State is managed within the
component
Analogy would be function
parameters Variable declared in the function
body
Props are immutable as passed from
parent to children State can be changed within
component
Props – Functional Components
this,props – Class Comoponents useState Hook – Functional
Components
this.state – Class Components
50
Class Component…State
Create Welcome.Js
import React,{Component} from 'react';
class Welcome extends Component {
render(){
retrun <h1>
Welcome Visitor
</h1>
}
}
export default Welcome;
Add a button, onclick page should display Thank you for subscribing
51
State…
Create a state object and initialize it
React components has a built-in state object.
The state object is where you store property values that belongs to the component.
When the state object changes, the component re-renders.
52
State…
import React,{Component} from 'react';
class Welcome extends Component {
constructor(){
super()
this.state={message:’welcome visitor’}
}
changeMessage(){
this.setState({
message: ‘Thank you for subscribing’
})
}
render(){
retrun (
<div>
<h1>{this.state.message}</h1>
<button onClick={()=>this.changeMessage()}>Subscribe</button>
</div>}}
53
setState…
Create new component Counter.js
import React,{Component} from 'react';
class Counter extends Component {
constructor(props){
super(props)
this.state={ count:0 } }
Increment(){
this.state.count=this.state.count+1
Console.log(this.state.count)
}
render(){
retrun (
<div>
<h1>counter - {this.state.count}</h1>
<button onClick={()=>this. Increment()}>Increment</button>
</div> } }
54
setState…..
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Counter from '/Counter‘
class App extends Component(){
render(){
return (
<div className="App">
<Counter/>
</div> );
}
export default App;
Never Change/modify the state directly, it ‘ll not be rendered, though incremented
value ‘ll be printed out on console.
55
setState… without callback
Counter.js
56
setState… with callback
Counter.js
render(){
retrun (
<div>
<h1>counter - {this.state.count}</h1>
<button onClick={()=>this. Increment()}>Increment</button>
</div> } }
57
setState…
Add a new method incrementFive in counter.js
incrementFive() {
this.increment()
this.increment()
this.increment()
this.increment()
this.increment()
}
----
render(){
retrun (
<div>
<h1>counter - {this.state.count}</h1>
<button onClick={()=>this. IncrementFive()}>Increment</button>
</div> } }
Output?
58
setState…Previous State
Counter.js
import React,{Component} from 'react';
class Counter extends Component {
constructor(props){
super(props)
this.state={ count:0 } }
Increment(){
//this.setState( {
//Count:this.state.count+1} , ( )=>{Console.log(‘call back //value’,this.state.count) })
this.setState( (prevState)=>({
count:prevState.count+1
}))
Console.log(this.state.count)
}
render(){
retrun (
<div>
<h1>counter - {this.state.count}</h1>
<button onClick={()=>this. Increment()}>Increment</button>
</div> } }
59
setState..Summary
Always make use of setState and never modify state
directly.
Code has to be executed after the state has been updated?
Place the code in the call back function which is the
second argument to the setState method.
When you have to update state based on the previous state
value, pass in a function as an argument instead of the
regular object.
60
Destructuring the props
import React from 'react';
const Greet =(props)=>{
return (
<h1>Hello {props.name} a.k.a {props.heroName}</h1>
{props.children}
)
}
-Destructing is an ES6 feature
-Two ways to destructure props in functional component
61
Destructuring….Functional Component
import React from 'react';
const Greet =({name,heroName})=>{
return (
<h1>Hello {name} a.k.a {heroName}</h1>
)
}
--------------
import React from 'react';
const Greet =(props)=>{
const {name, heroName}=props
return (
<h1>Hello {name} a.k.a {heroName}</h1>
{props.children}
)
}
62
Destructuring….Class Component
import React,{Component} from 'react';
class Greet extends Component {
render(){
retrun <h1>Hello {this.props.name} a.k.s
{this.props.heroName} </h1>
}
}
export default Greet;
-- in class destructing is done in render method.
63
Destructuring….
import React,{Component} from 'react';
class Greet extends Component {
render(){
const {name,heroName}=this.props
//likewise states
//const {state1, state2}= this.state
retrun <h1>Hello {name} a.k.s {heroName} </h1>
}
}
export default Greet;
64
Event Handling
Just like HTML, React can perform actions based on user
events.
Mouse clicks, mouseover, key press etc
React events are written in camelCase syntax:
65
Event Handling….Functional Component
FunctionClick.js
import React from 'react';
function FunctionCick() {
Function clickHandler(){
console.log(‘Button Clicked’)
}
retrun (
<div>
<button onClick={clickHandler}>Click</button>
</div>
}
export default FunctionClick;
If you write <button onClick={clickHandler()}>Click</button> by mistake then
what is going to happen?
66
Event Handling….
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import FunctionClick from '/FunctionClick‘
class App extends Component(){
render(){
return (
<div className="App">
< FunctionClick/>
</div> );
}
export default App;
67
Event Handling..Class Component
ClassClick.js
import React from 'react';
class ClassClick extends Component {
clickHandler(){
console.log(‘Clicked the button’)
}
render(){
retrun (
<div>
<button onClick={this.clickHandler}>Click me</button>
</div>
}
}
export default ClassClick;
68
Event Handling….
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import ClassClick from '/ ClassClick‘
class App extends Component(){
render(){
return (
<div className="App">
< ClassClick />
</div> );
}
export default App;
69
Binding Event Handlers
EventBind.js
import React,{Component} from 'react';
class EventBind extends Component {
constructor(props){ super(props)
this.state={ message:’Hello’ } }
clickHandler{
this.setState({
message: ‘Good Bye’
})}
render(){
<div><div>this.state.message</div>
<button onClick={this.clickHandler}>Click</button>
71
Binding Event Handler….
EventBind.js ..2) Use Arrow Function to call handler in render method
import React,{Component} from 'react';
class EventBind extends Component {
constructor(props){ super(props)
this.state={ message:’Hello’ } }
clickHandler{
this.setState({
message: ‘Good Bye’
})}
render(){
<div><div>this.state.message</div>
//<button onClick={this.clickHandler.bind(this) }>Click</button>
<button onClick={()=>this.clickHandler()}>Click</button></div>}
72
Binding Event Handler…
EventBind.js ..3) Binding event handler in constructor method
import React,{Component} from 'react';
73
Binding Event Handler…..
EventBind.js ..4) Use arrow function as class property
import React,{Component} from 'react';
74
So far topics covered in React
Basic structure of React application/project
ES6
Components
JSX
Props
State
setState
Destructuring
Event Handling
Binding Event Handler
75
Any Question?
76