Lecture # 13 - React - Part II: Advanced Programming
Lecture # 13 - React - Part II: Advanced Programming
Advanced Programming
1
Question?
2
Method as Props (reference)
ParentComponent.js
import React, {Component} from 'react';
import ChildComponent from ‘./ChildComponent’
class ParentComponent extends Component {
constructor(props){
super(props)
this.state={ parentName:’Parent’ }
this.greetParent=this.greetParent.bind(this)
}
greetParent() {
alert(‘Hello’ +this.state.parentName)
}
render(){ return(<div><ChildComponent greetHandler={this.greetParent} /></div>
)}
3
Method as Props…..
ChildComponent.js
import React from 'react';
function ChildComponent(props) {
return (
<div>
<button onClick={props.greetHandler}>greet
parent</button>
</div>
}
export default ChildComponent;
4
Method as Props…
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import ParentComponent from '/ ParentComponent ‘
class App extends Component(){
render(){
return (
<div className="App">
< ParentComponent />
</div> );
}
export default App;
5
Method as Props…Pass Parameters
When calling method in parent from child component and need to pass
parameters/arguments.
Arrow function in the return statement is useful
Arrow function are simplest way to pass parameter from child to parent
component
import React from 'react';
function ChildComponent(props) {
retrun (
<div>
<button onClick={()=>props.greetHandler(‘Child’)}>great parent</button>
</div>
}
export default ChildComponent;
6
Method as Props…Pass Parameters
ParentComponent.js
import React from 'react';
Import ChildComponent from ‘./ChildComponent’
7
Conditional Rendering
Hide or Show some HTML based on any condition
React Supports Conditional Rendering
If –else
Element Variable
Ternary Conditional Operator
Short Circuit Operator
8
IF- Else
UserGreeting
import React,{Component} from 'react';
class UserGreeting extends Component {
constructor(props)
{ super (props)
this.state={isLoggedIn:false}
}render(){ if(this.state.isLoggedIn){
return(<div>Welcome Naheeda</div>) }
else { return(<div>Welcome Guest</div>)
}}
}export default UserGreeting
* If can’t be embedded inside JSX so separate return statements
9
Element Variable
import React,{Component} from 'react';
class UserGreeting extends Component {
constructor(props)
{ super(props)
this.state={isLoggedIn:true} }
render(){
let message
if (this.state.isLoggedIn){ message=<div>Welcome Naheeda</div>}
else { message=<div>Welcome Guest</div> }
return <div>{message}</div>
}
}export default UserGreeting
10
Ternary Conditional Operator
import React,{Component} from 'react';
class UserGreeting extends Component {
constructor(props)
{
super(props)
this.state={isLoggedIn:true}
}
render(){
return this.state.isLoggedIn?(
<div>Welcome Naheeda</div>
):(
<div>Welcome Guest</div>)
}
}
export default UserGreeting
11
Short Circuit Operator
Simple case of Ternary Operator
Either show or does‘t show the element
12
List Rendering
Common scenario is to display the list of items e.g list of name, list of
courses, list of products
Recall Array in JS
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
var array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Transformation using map method
This pure JS feature
Map method take function as an argument
13
List Rendering….
import React from 'react';
function NameList() {
const names=['Muhammad', 'Aslam', 'Akram']
return (
<div>
<h2>{names[0]}</h2>
<h2>{names[1]}</h2>
<h2>{names[1]}</h2>
</div> )
}
export default NameList
14
List Rendering….
import React from 'react';
function NameList() {
const names=['Muhammad', 'Aslam', 'Akram']
return (
<div>{
names.map(name=><h2>{name}</h2>) }
</div> )
}
export default NameList
name can be of your choice of argument but keep it relevant to your
code
<h2>{name}</h2> is the return statement
15
List Rendering… Simplify the Code
import React from 'react';
function NameList() {
const names=['Muhammad', 'Aslam', 'Akram']
const nameList =names.map(name=><h2>{name}</h2>)
return <div> {nameList} </div>
}
export default NameList
16
List Rendering…
Display complete object detail like name, age,skill of each
person….
Example code
17
Lists and Keys
Every object in list should have unique key prop
Key can’t be accessed in child component
18
List and Keys…
Try this and check out put? Will key rendered
import React from 'react';
function Person({person,key}) {
return (
<div>
<h2> {key} I am {person.name}. I am {person.age} years old.
I know {person.skill}
</h2>
</div>)
}
export default Person
19
List and Keys…
20
List and Keys….
List without key attribute
<ul> <ul>
<li>Aslam </li> <li>Aslam </li>
<li>Akram</li> <li>Akram</li>
</ul> <li>Muhammad</li>
</ul>
<ul> <ul>
<li>Aslam </li> <li>Muhammad</li>
<li>Akram</li> <li>Aslam </li>
</ul> <li>Akram</li>
</ul>
21
List and Keys….
List with key attribute
<ul> <ul>
<li key=“1”>Aslam </li> <li key=“3”>Muhammad</li>
<li key=“2”>Akram</li> <li key=“1”>Aslam </li>
</ul> <li key=“2”>Akram</li>
</ul>
22
Index as key…
import React from 'react';
function NameList() {
const names=['Muhammad', 'Aslam', 'Akram','Muhammad']
const nameList =names.map((name,index)=><h2
key={index}>{index}{name}</h2>)
return <div> {nameList} </div>
}
export default NameList
23
Index as Key….Challenge
Add item at the start of the list, When updating UI, React
thinks it already have three
<ul> items with 0, 1,2 keys.
<ul>
<li
<li
key=“0”></li>
<ul> key=“0”>1</li>
<li
<li key=“0”>1 </li> <li
key=“1”></li>
<li key=“1”>2</li> key=“1”>2</li>
<li key=“2”>3</li> <li
<li
</ul> key=“2”></li>
key=“2”>3</li>
<li
<li key=“3”></li>
key=“3”></li>
</ul>
</ul>
24
Index as Key…
When to use index as key?
The items in your list do not have a unique id
The List is static list and will not change
The list will never be reordered or filtered
25
Styling React Components
CSS stylesheets
Inline Stlying through style attribute
CSS modules
26
Style… Css classes
App.css
body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Arial;
text-align: center;
}
import './App.css‘ where you want to use, className
property.
27
Styling…Inline
class MyHeader extends React.Component {
render() {
return (
<div>
<h1 style={{color: "red"}}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
28
Styling…. CSS module
Create the CSS module with the .module.css extension,
example: mystyle.module.css.
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Arial;
text-align: center;
}
29
Styling…. CSS module
import React,{Component} from 'react';
import styles from './mystyle.module.css';
30
React Forms…
import React,{Component} from 'react';
class ReactForm extends Component {
render() {
return (
<form>
<h1>Hello</h1>
<p>Enter your name:</p>
<input
type="text"/>
</form>
)
}
}
export default ReactForm
31
React Forms…
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { username: '' }; }
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.username); }
myChangeHandler = (event) => {
this.setState({username: event.target.value}); }
render() {
return ( <form onSubmit={this.mySubmitHandler}>
<h1>Hello {this.state.username}</h1>
<p>Enter your name, and submit:</p>
<input type='text' onChange={this.myChangeHandler} />
<input type='submit' /> </form> ); } }
32
Component Lifecycle Methods
Each component in React has a lifecycle which you can
monitor and manipulate during its three main phases.
Mainly for Class Component
Mounting When an instance of the component is being
created and inserted into the DOM
Updating When a component is being re rendered as a result
of changes to either its props or state
Unmounting When a component is being removed from
DOM
Error Handling When there is an error during rendering, in
lifecycle method, or in the constructor of any child component
33
Component Lifecycle….
Mounting constructor(), getDerivedStateFromProps() ,
render(), componentDidMount()
Updating getDerivedStateFromProps(),
shouldComponentUpdate(), render(),
getSnapshotBeforeUpdate(), componentDidUpdate()
Unmounting
componentWillUnmount()
Error Handling
34
Mounting Lifecycle Methods….
constructor(props)
A special Function that will called whenever a new
component is created.
Initialize State
Binding the Event Handlers
Super(props). When you add your constructor. Call super
method first. Then this. Props can be accessed.
Directly Overwrite this.state
35
Mounting Lifecycle Methods….
getDerivedStatefromProps (props , state)
According to React Documentation, it is rarely used
method.
Used when the state of the component depends on
changes in props over time.
This is the natural place to set the state object based on the
initial props.
It takes state as an argument, and returns an object with
changes to the state.
36
Mounting Lifecycle Methods….
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
In App.js <Header favcol="yellow"/>
* Called just before render method
37
Mounting Lifecycle Methods….
render()
The render() method is required, and is the method that
actual outputs HTML to the DOM.
Only required component
componentDidMount
The componentDidMount() method is called after the
component is rendered.
This is where you run statements that requires that the
component is already placed in the DOM
Called only once in the lifecycle of the component
38
Mounting Lifecycle Methods….
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
39
Mounting Lifecycle Methods….
Question:
What
will be order of Execution when A
component has child component?
40
Component Updating Lifecycle Methods
The next phase in the lifecycle is when a component is
updated.
A component is updated whenever there is a change in the
component's state or props.
The render() method is required and will always be called,
the others are optional and will be called if you define
them.
41
Component Updating…
getDerivedStatefromProps (props , state)
Same as discussed earlier, Method is called every time
when a component is re rendered
shouldComponentUpdate (nextProps, nextState)
Dictates if the component should re render or not
By Default component re render when there is state or
props change.
This method can prevent default re rendering by returning
false.
42
Component Updating…
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"}; }
shouldComponentUpdate() {
return false; }
changeColor = () => {
this.setState({favoritecolor: "blue"});
} render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
); }}
43
Component Updating…
render()
Only required method, already familiar.
getSnapshotBeforeUpdate(prevProps, prevState)
In the getSnapshotBeforeUpdate() method you have
access to the props and state before the update, meaning
that even after the update, you can check what the values
were before the update.
If the getSnapshotBeforeUpdate() method is present, you
should also include the componentDidUpdate() method,
otherwise you will get an error.
44
Component Updating…
componentDidUpdate()
Called when the render is finished in the re render cycles
Called only once
45
Component Updating…
Practice W3school examples of Updating
46
Unmounting Phase Methods
The next phase in the lifecycle is when a component is
removed from the DOM, or unmounting as React likes to
call it.
React has only one built-in method that gets called
immediately before when a component is unmounted:
componentWillUnmount()
Don’t call setState in it as its never going to re render
47
Error Handling Phase Methods
getDerivedStateFromError()
componentDidCatch()
Both methods are called when there is an error during
rendering, in a lifecycle method, or in the constructor of
any child component.
48
Any Question?...
49