Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Components

Components are building block of apps. Components describe a part of the user
interface. They are reusable and can be nested inside other components.

Like header, footer, side nav, main content they all form part of root components which
is often called as app component.

Types

1. Functional component

 Simple functions
 Use functional component as much as possible
 Absence of this keyword
 State full

Example

import React from 'react'


// function Greet(){
// return <h1>Hello Navi</h1>
// return <h2>I am Naveed</h2>
// }
const Greet=()=><h1>Hello naveed</h1>

export default Greet

2. Class component

 More feature rich


 Maintain their own private data –state
 Complex UI logic
 Provide lifecycle hooks
 State full /Smart/ Container

import React,{Component} from "react";


class Welcome extends Component{
render(){
return <h1>Class Component</h1>
}
}
export default Welcome

JSX

JavaScript XML (JSX) – Extension to the JS language syntax.

Write XML – Like code for elements and components.

JSX tags have a tag name, attributes and children.

JSX ultimately trans piles to pure JS which is understood by the browser.

const Hello=()=>{
return (
<div className="DummyClass">
<h1>Hello Naveed Akram</h1>
</div>
)
}

WITHOUT JSX

const Hello=()=>{
return React.createElement("div",
{id: 'Hello' , className: 'dummyclass'},React.createElement('h1',null,'hello
Naveed Akram'))

Properties (Props)

Props are optional input which your component can accept. Props is object and has
attributes passed from parent component. Props are immutable (their value cannot be
changed).

Syntax of using Props in Functions and Classes


React file

import logo from "./logo.svg";


import "./App.css";
import Greet from "./Component/Greet";
import Welcome from "./Component/Welcome";
import Hello from "./Component/Hello"
function App() {
return (
<div className="App">
<Greet name="Naveed" heroName="Batman"/>
<p>This is childern props</p>
<Greet/>
<Greet name="Ali" heroName="Cylian Murphy"/>
<button>Action</button>
<Greet/>
<Welcome name="Naveed" heroName="Batman"/>
<Welcome name="Ali" heroName="Cylian Murphy"/>
{/* <Hello/> */}
</div>
);
}

export default App;

Functions using Props

import React from 'react'


// function Greet(){
// return <h1>Hello Navi</h1>
// return <h2>I am Naveed</h2>
// }

const Greet=(props)=>{
console.log(props)

return(
<div>
<h1>Hello {props.name} a.k.a {props.heroName}
{props.childern}
</h1>
</div>
)
}
export default Greet

Classes using Props

import React, { Component } from "react";


class Welcome extends Component {
render() {
return <h1>{this.props.name} a.k.a {this.props.heroName}</h1>;
}
}
export default Welcome;

Props State
Props get passed to the component State is managed within the component
Functions parameters Variables declared in the function body
Props are immutable State can be changed
Props –functional components UseState Hook – Functional Components
this.props – Class Components this.state –Class Components

Example Code

import React, { Component } from "react";


import Welcome from "./Welcome";
class Message extends Component {
constructor(){
super()
this.state={
message : 'Welcome Visitor',
}
}
changeMessage(){//Message to be shown on click regarding change state
this.setState({
message: 'Thank you for Subscribing'
})
}
render() {//render and return methods
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={()=>this.changeMessage()}>Subscribe</button>

</div>

)
}
}
export default Message;

SETSTATE

SetState is used to update the value of GUI using some method and changing it on any
event like click etc.

DO’s

 Always make use of setState and never modify the state directly.
 Code has to be executed after the state has been updated? Place that code in
the call back function which is the second argument to the setState method.
 When you have to update state on the previous state value, in a function as an
argument instead of the regular object.

Example Code

import React, { Component } from "react";


class Counter extends Component {
constructor(props){//Creating a constructor
super(props)//Invoking parent class Component constructor
this.state={//Assigning a attribute object in constructor
count : 0
}
}
Increment (){//Increment method to change the state
// this.setState({
// count: this.state.count+1
// },
// ()=>{
// console.log("Your value as per async is "+this.state.count)
// }
// )
this.setState(prevState=>({
count: prevState.count+1
}))
console.log(this.state.count)
}
IncrementFive(){
this.Increment ()
this.Increment ()
this.Increment ()
this.Increment ()
this.Increment ()
}

render() {
return (
<div>
<div>count - {this.state.count}</div>
<button onClick={()=>this.IncrementFive()}>Increment</button>
</div>

)
}
}
export default Counter;

DE structuring in React functions

const Greet=(props)=>{
const {name,heroName}=props
return (
<div>
<h1>Hello {name} a.k.a {heroName}
</h1>
</div>
)
}

DE structuring in React Classes


class Welcome extends Component {
render() {
const {name,heroName}=this.props
return <h1>{name} a.k.a {heroName}</h1>;
}
}

Event Handling on JS

In Classes

class ClassClick extends Component {


clickHandler(){
console.log("Button pressed");
}
render() {

return (
<div>
<button onClick={this.clickHandler}>Click Me</button>//()no brackets in
front of method
</div>
)
}
}

In Functions

function FunctionClick() {
function clickHandler(){
console.log("I am Clicked")
}
return (
<div>
<button onClick={clickHandler}>Click</button>//onClick in camelCase
</div>
)
}

Event Binding in React


There are four ways to bind events in JS.

1. In render method

2. In render as arrow function

3. In class constructor. This is best

4. In class as arrow

class EventBind extends Component {


constructor(props) {
super(props)

this.state = {
message:"Hello"
}

this.clickHandler=this.clickHandler.bind(this)//Binding in class
constructor
}
// clickHandler(){//Best option uptill now
// this.setState({//Changing state
// message:"Good Bye"
// })
// }
clickHandler=()=>{//Another approach to bind the event handling
this.setState({//Changing state
message:"Good Bye"
})
}
render() {
return (
<div>
<div>
{this.state.message}
</div>
<button onClick={this.clickHandler}>Click</button>

</div>
)
}
}
export default EventBind

Method as Props

We can declare a method in child and then use it for child.

Example of Parent

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);//Event Binding
}

greetParent(childName){
alert(`Hello ${this.state.ParentName} from ${childName}`)
}

render() {
return (
<div>
<ChildComponent greetHandler={this.greetParent}/>
</div>
)
}
}

export default ParentComponent

Example of Child using it

import React from 'react'

function ChildComponent(props) {
return (
<div>
<button onClick={()=>props.greetHandler('Child')}>greetParent</button>
</div>
)
}

export default ChildComponent

Conditional Rendering
If/else
It is based on some decision making and then showing HTML depend on
condition which is true.
class UserGreeting extends Component {
constructor(props) {// Use rconst for construcor snippet
super(props);

this.state = {
IsLoggedIn: true,// defining a props
};
}

render() {//definig conditional rendering


if (this.state.IsLoggedIn) {
return <div>Welcome Naveed</div>;
} else {
return <div>Welcome Guest</div>;
}
}
}

export default UserGreeting;

Elements variable
This approach is used in the form of a variable in which message is stored
in the form variable and then HTML is displayed from variable.
class UserGreeting extends Component {
constructor(props) {// Use rconst for construcor snippet
super(props);

this.state = {
IsLoggedIn: false,// defining a props
};
}

render() {//definig conditional rendering


let message//Declaring variable
if(this.state.IsLoggedIn){
message=<div>
Welcome Naveed
</div>
}
else{
message=<div>
Welcome Guest
</div>
}
return <div>{message}</div>//returning message based on decision
}
}

export default UserGreeting;

Ternary Conditional Operator


Condition true first line executed if false second line is executed.
import React, { Component } from "react";//use rce for class snippt

class UserGreeting extends Component {


constructor(props) {// Use rconst for construcor snippet
super(props);

this.state = {
IsLoggedIn: false,// defining a props
};
}

render() {//definig conditional rendering


return(
this.state.IsLoggedIn ?(//If condition is true first statement is
returned
<div>Welcome Naveed</div>
)
:
(<div>Welcome Guest</div>)//If false second condition is retu

)
}
}

export default UserGreeting;

Short Circuit Operators


Short circuit is used for rendering something or nothing based on situation
if true will return something otherwise nothing.

this.state.IsLoggedIn && <div>Welcome Naveed</div>// First LHS is evualted if


true then RHS is evualted.

How to render List in HTML?


import React from "react";

function NameList() {
const names = ["Naveed", "Ali", "Ahmed"]; //declaring array
const NameList = names.map((name) => <h2>{name}</h2>); //applying map method
on to show list with h2 tag
return <div>{NameList}</div>; //Displaying namelist JSX
}

export default NameList;

List and Keys


1. A key is a special string attribute you need to include when creating list of
elements.
2. Key give the elements a stable identity.
3. Key help React identify which items have changed, are added or are removed.
4. help in efficient update of the user interface.
import React from "react";
import Person from "./Person";

function NameList() {
const persons = [
{
rollno: 1,
name: "Naveed",
age: 30,
section: "A",
},
{
rollno: 2,
name: "ALI",
age: 20,
section: "B",
},
{
rollno: 3,
name: "Ahmer",
age: 25,
section: "C",
},
];

const personList = persons.map((person) => <Person key={person.rollno}


person={person} />);//Assigning key which is unique for everyone
return <div>{personList}</div>;
}

export default NameList;

Index of Array as Key


First of all, avoid using index as key. Go for unique id if you have one. If at
all you want to use it then it must fulfill these conditions.
Conditions
1. The item in your list do not have a unique id.
2. The list is a static list and will not change.
3. The list will never be reordered or filtered.
function NameList() {
const names = ["Naveed", "Ali", "Ahmer","Ali"];
const nameList = names.map((name,index) => <h2 key={index }> {name}</h2>)//Add
parameters to arrow function
return (
<div>
{nameList}
</div>
);
}

Life Cycle Methods


1. Mounting
2. Updating
3. Unmounting
4. Errors
Mounting Life Cycle Methods
1. Constructor
a. A special function that will get called whenever a new component is
created.
b. It is used for initializing state.
c. Binding the event handlers.
d. Do not cause side effects. Ex: HTTP requests.
e. A call to base class constructor is must using super(props).
2. static getDerivedStatefromprops(props,state)
a. When the state of the component depends on changes in props over time.
b. Set the state.
c. Do not cause side effects. Ex: HTTP requests.
3. render()
a. Only required method.
b. Read props & state and return JSX.
c. Do not change state or interact with DOM or make ajax calls.
d. Children components lifecycle methods are also executed.
componentDidMount()
a. Invoked immediately after a component and all its children componets have been
rendered to the DOM.
b. Cause side effects Ex: Interact with the DOM or perform any ajax calls to load
data.
Example Code for Above
class LifeCycleA extends Component {
constructor(props) {
super(props);

this.state = {
name: "naveed",
};
console.log("Life cycle Construtor A");
}
static getDerivedStateFromProps(props,state){
console.log('static getDerivedStatefromprops A')
return null
}
componentDidMount() {
console.log("Componet did mount A");
}
render() {
console.log("Render method A");
return(
<div>LifeCycleA
<LifeCycleB/>
</div>
)
}
}

export default LifeCycleA;

Updating Life Cycle Methods


1. static getDerivedStatefromprops(props,state)
a. When the state of the component depends on changes in props over time.
b. Method is called every time a component is re-render.
c. Do not cause side effects. Ex: HTTP requests.
2. shouldComponentUpdate(nextProps,nextState)
a. Dictates if the component should re render or not.
b. Performance optimization.
c. Do not cause side effects. Ex: HTTP requests.
3. render()
a. Only required methods
b. Read props & state and return JSX
c. Do not cause side effects. Ex: HTTP requests.
4. getSnapshotBeforeUpdate(prevProps, prevState )
a. Called right before the changes from the virtual DOM are to be
reflected in the DOM.
b. Capture some information from the DOM.
c. Method will either return null or some value. Returned value will passed as
third parameter to next method.
5. componentDidUpdate(prevProps,prevState,snapshots)
a. Called after the render is finished in the re-render cycles.
b. Cause side effects.
Example code
import React, { Component } from "react";
import LifeCycleB from "./LifeCycleB";

class LifeCycleA extends Component {


constructor(props) {
super(props);

this.state = {
name: "naveed",
};
console.log("Life cycle Construtor A");
}
static getDerivedStateFromProps(props,state){
console.log('static getDerivedStatefromprops A')
return null
}
componentDidMount() {
console.log("Componet did mount A");
}
shouldComponentUpdate(nextProps,nextState){
console.log("shouldComponentUpdate from A")
return true
}
getSnapshotBeforeUpdate(prevProps, prevState ){
console.log('getSnapshotBeforeUpdate from A')
return null
}
componentDidUpdate(prevProps,prevState,snapshots){
console.log('componentDidUpdate from A')
}
changeState=()=>{
this.setState({
name:"React course"
})
}
render() {
console.log("Render method A");
return(
<div>
<div>LifeCycleA</div>
<button onClick={this.changeState}>Change on CLick</button>
<LifeCycleB/>
</div>
)
}
}

export default LifeCycleA;

Unmounting Phase Method


componentWillUnmount()
a. Method is invoked immediately before a component is unmounted and
destroyed.
b. Used for cancelling any network requests, removing event handlers, cancelling
any subscriptions and also invalidating timers.
c. Do not call the setState method.
Memo in React
React Memo is a higher-order component that wraps around a component to memoize
the rendered output and avoid unnecessary renderings. This improves performance

because it memoizes the result and skips rendering to reuse the last rendered result.

When to Use it
 Use React Memo if your component will render quite often.
 Use it when your component often renders with the same props. This happens to
child components who are forced to re-render with the same props whenever the
parent component renders.
 Use it in pure functional components alone. If you are using a class component,
use the React.PureComponent.
 Use it if your component is big enough (contains a decent amount of UI
elements) to have props equality check.
Syntax
import React from 'react'

function MemoComp({name}) {//de structuring


console.log("Rendering Memo Component")
return (
<div>
{name}
</div>
)
}

export default React.memo(MemoComp)//Add react.memo and wrap file in parathesis

You might also like