Unit IV-Advanced Client Side Programming
Unit IV-Advanced Client Side Programming
Agenda
• React JS:ReactDOM
• JSX – Components
• Local storage
• Events
Introduction
Introduction
• React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
• Declarative: React makes it painless to create interactive UIs. Design simple views for each state in
your application and React efficiently update and render just the right components when your data
changes. Declarative views make your code more predictable and easier to debug.
• ReactJS is an open-source, component-based front-end library responsible only for the view layer of
the application.
• Component-based: Build encapsulated components that manage their own state, then compose them
to make complex UIs. Since components logic written JavaScript library instead of templates, you can
easily pass rich data through your app and keep state out of the DOM.
6 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
Introduction
• Developed at Facebook and released to the world in 2013, it drives some of the most widely used apps,
• Its primary goal is to make it easy to reason about an interface and its state at any point in time, by
• ReactJS uses virtual DOM based mechanism to fill in data (views) in HTML DOM.
• The virtual DOM works fast owning to the fact that it only changes individual DOM elements instead of
7 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
Introduction
• A React application is made up of multiple components, each responsible for outputting a small,
reusable piece of HTML.
• Components can be nested within other components to allow complex applications to be built out of
simple building blocks.
• JSX allows us to write our components using HTML, whilst mixing in JavaScript events.
• React will internally convert this into a virtual DOM and will ultimately output our HTML for us.
• By doing most of the processing inside the virtual DOM rather than directly in the browser's DOM, React
can act quickly and only add, update, and remove components which have changed since the last
render cycle occurred.
8 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
● Create React application with the following command, (application name- mycounterapp)
cd mycounterapp
npm start
In React application, there are several files and folders in the root
11 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
• src: It contains the App.css, App.js, App.test.js, index.css, index.js, and serviceWorker.js files. Here,
the App.js file always responsible for displaying the output screen in React.
• package-lock.json: It is generated automatically for any operations where npm package modifies
either the node_modules tree or package.json. It cannot be published. It will be ignored if it finds any
• package.json: It holds various metadata required for the project. It gives information to npm, which
12 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
ReactDOM
• ReactDOM is a package provided by React that enables interaction with the DOM (Document Object
Model) in web applications. It’s typically used to render React components into the actual HTML page.
root.render(<App />);
13 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
- index.js
Replace all the content inside the <div className="App"> with a <h1> element as follows,
File name: App.js
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<p>
<h1>hello world</h1>
</p>
</header>
</div>
);}
export default App;
React Features
• Currently, ReactJS gaining quick popularity as the best JavaScript framework among web
developers.
● JSX
● Components
● Virtual DOM
● Simplicity
● Performance
16 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
React Features
JSX
• It extends the ES6 so that HTML like text can co-exist with JavaScript react code.
17 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
React Features
Components
• ReactJS application is made up of multiple components, and each component has its own logic and
controls.
• These components can be reusable which help you to maintain the code when working on larger scale
projects.
18 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
React Features
• ReactJS is designed in such a manner that follows unidirectional data flow or one-way data binding.
• The benefits of one-way data binding give you better control throughout the application.
• It is because components are supposed to be immutable and the data within them cannot be changed.
• Flux is a pattern that helps to keep your data unidirectional. This makes the application more flexible
19 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
React Features
Virtual DOM
• Whenever any modifications happen in the web application, the entire UI is re-rendered in virtual DOM
representation.
• Then it checks the difference between the previous DOM representation and the new DOM.
• Once it has done, the real DOM will update only the things that have actually changed.
20 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
React Features
Simplicity
• ReactJS uses JSX file which makes the application simple and to code as well as understand.
• We know that ReactJS is a component-based approach which makes the code reusable as your need.
21 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React
React Features
Performance
• This feature makes it much better than other frameworks out there today.
• The DOM is a cross-platform and programming API which deals with HTML, XML or XHTML.
• Due to this, when we create a component, we did not write directly to the DOM.
• Instead, we are writing virtual components that will turn into the DOM leading to smoother and faster
performance.
22 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
Function component
• A Function component also returns HTML and behaves much the same way as a Class component.
• Function components can be written using much less code, are easier to understand.
function Greetings() {
Note: Component names should start with capital letter. (Example: Car, Greet, App…)
24 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
Rendering a Component
• To use this component in your application, use similar syntax as normal HTML:
root.render(<Greetings />);
25 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
Components in Components
function Greetings() {
return <h2>Happy Birthday..!</h2>;
}
function Wish() {
return (
<div>
<h1>Wishes for you…</h1>
< Greetings />
</div>
);
}
26 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
Components in Files
• React is all about re-using code, and it is recommended to split your components into separate files.
• To do that, create a new file with a .js file extension and put the code inside it.
• The filename must start with an uppercase character. Component should be exported at the end of file.
function Greetings() {
27 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
• Your React app is taking shape with many components being nested within each other.
• Thinking of your app as a tree is useful for understanding the relationship between components. This
understanding will help you debug future concepts like performance and state management.
• Here, the root is the starting component, and each of the other pieces becomes branches, which are
further divided into sub-branches.
28 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
Your UI as a tree
• Trees are a relationship model between items, and UI is often represented using tree structures. For
example, browsers use tree structures to model HTML (DOM) and CSS (CSSOM).
• React also uses tree structures to manage and model the relationship between components in a React
app.
• These trees are useful tools to understand how data flows through a React app and how to optimize
rendering and app size.
29 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
• As we nest components, we have the concept of parent and child components, where each parent
component may itself be a child of another component.
• When we render a React app, we can model this relationship in a tree, known as the render tree.
30 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
•//Filename:
- App.js <div>
function App() { );
return ( }
31 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
•//Filename:
- Header.js
function Header() {
32 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
•// filename:
- Main.js <main>
function Main() { );
return ( }
33 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
•// filename:
- Sidebar.js // filename: Content.js
function Sidebar() {
34 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
•// filename
- : Footer.js
function Footer() {
35 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI
• This tree shows the hierarchical structure of components, which React uses to efficiently render and
update the DOM.
36 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
What is JSX?
the React framework that allows you to structure the rendering of elements.
• Due to its flexibility, JSX has been adopted by other popular frameworks such as Vue.js throughout
the years.
• The syntax is intended to be used by preprocessors to transform HTML-like text found in JavaScript
files into standard JavaScript objects that a JavaScript engine will parse.
38 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
Why JSX?
• React separates concerns with loosely coupled units called “components” that contain both markup
• JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file,
just like XML/HTML, JSX tags have a tag name, attributes, and children.
• It is faster than regular JavaScript because it performs optimization while translating the code to
JavaScript.
39 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
Coding JSX
• JSX allows us to write HTML elements in JavaScript and place them in the DOM without
• As it is an extension of the JavaScript language based on ES6, it is translated into regular JavaScript
at runtime.
• Here are two examples. The first uses JSX and the second does not:
40 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
• JSX is a syntax extension that looks like HTML and makes React code more readable.
• However, React can also be written using React.createElement() directly, which is what JSX compiles
41 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
Note: You are not required to use JSX, but JSX makes it easier to write React applications.
42 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
43 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
Rendering Elements
• Applications built with just React usually have a single root DOM node.
• To render a React element, first pass the DOM element to ReactDOM.createRoot(), then pass the
• render() is the most used method for any React powered component which returns a JSX with
backend data.
44 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
• To use more than one element, you need to wrap it with one container element.
• Here, we use div as a container element which has three nested elements inside it.
import React, { Component } from 'react';
class App extends Component{
render(){
return(
<div>
<h1>Welcome</h1>
<h2>Training Institutes</h2>
<p>This website contains the best React tutorials.</p>
</div>
);
}
}
export default App;
45 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
Expressions in JSX
• The expression can be a React variable, or property, or any other valid JavaScript expression.
46 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
If statements in JSX
• React supports if statements, but not inside JSX. To be able to use conditional statements in JSX,
you should put the if statements outside of the JSX, or you could use a ternary expression instead:
import React from 'react’; import React from 'react’;
const x = 5; const x = 5;
let text = "Goodbye"; const myElement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;
if (x < 10) { function App (){
text = "Hello"; return(
} myElement
const myElement = <h1>{text}</h1>; );
function App (){ }
return( }
myElement export default App;
);
}
export default App;
48 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Rules
• Return a single root element.
• To return multiple elements from a component, wrap them with a single parent tag.
• For example, you can use a container <div> and </div> or a fragment <> and </>. Fragments let you group
things without leaving any trace in the browser HTML tree
• We can also use our own custom attributes in JSX. For custom attributes, we need to use data- prefix.
49 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
//jsx
function App() {
// Rendered HTML
50 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Comments
• JSX allows us to use comments that begin with /* and ends with */ and wrapping them in curly
braces {} just like in the case of JSX expressions. Below example shows how to use comments in JSX
51 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Styling
• There are various strategies to follow when planning to style React components, these strategies have
1. Inline styling
2. Style Object
3. CSS stylesheets
4. CSS Modules
5. SASS
52 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Styling
1. Inline styling
• If you are familiar with basic HTML, you’ll know that it is possible to add your CSS inline.
• These styles are written as attributes and are passed to the element.
53 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
function App() {
return (
<div>
</h1>
</div>
);
54 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Styling
• We create a style object variable the same way we create a JavaScript object.
• This object is then passed to the style attribute of the element we want to style.
• So instead of adding the styles inline directly, as we did in the previous example, we just pass the
object variables:
55 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
56 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Styling
3. CSS Stylesheet
• You can write your CSS styling in a separate file, just save the file with the .css file extension and
• Create a new file called "App.css" and insert some CSS code in it:
• You can call the file whatever you like, just remember the correct file extension.
57 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
import "./styles.css";
return (
<div>
</div>
);
58 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Styling
4. CSS Modules
• Another way of adding styles to your application is to use CSS Modules.
• CSS Modules are convenient for components that are placed in separate files.
• The CSS inside a module is available only for the component that imported it, and you do not have
to worry about name conflicts.
• Create the CSS module with the .module.css extension, example: my-style.module.css.
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
}
59 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
60 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Styling
5. SASS
• Another way of styling is using SASS (Syntactically Awesome Style Sheets) preprocessors with the
react project.
– Ex: MyComponent.module.css
61 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
JSX Styling
5. SASS
import React from "react";
import MyComponent from "./MyComponent";
function App() {
return (
<div className="App">
<MyComponent />
</div>
);
}
export default App;
App.js
62 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX
MyComponent.js MyComponent.module.scss
import React from "react"; .myComponent {
import styles from "./MyComponent.module.scss"; background-color: #f0f0f0;
function MyComponent() { padding: 20px;
return ( border-radius: 8px;
<div className={styles.myComponent}> box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
<h1>Hello, React with SCSS!</h1>
<p>This is a simple example.</p> h1 {
</div> color: #333;
); margin-bottom: 10px;
} }
p { color: #a40f0f; }
export default MyComponent; }
63 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s
Props
Please download pictures in
suitable size here and insert them
by clicking the symbol above.
props
function Car(props) {
65 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
props
• -
//file name: app.js
import React from 'react';
import Greeting from './Greeting';
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
export default App;
66 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
props
• -
//Output
function Greeting(props) { Hello, Alice!
return <h1>Hello, {props.name}!</h1>; Hello, Bob!
}
67 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
Multiple props
// Render
// Output
Welcome, Aliens!
68 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
Values of Props
• But often you'd like to set props to values like numbers, Booleans, objects, arrays, and even variables.
• React doesn't put any restriction on what value a prop can have.
• All values, except double-quoted string literals, must be wrapped in curly braces prop={value}.
String Literals:
<MyComponent prop="My String Value">
Values of Props
70 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
function Car(props) {
return <h2>I am a { props.brand}!</h2>;
}
function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}
71 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}
72 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
Passing JSX
//card.js //parent.js
import React from 'react'; import React from 'react';
function Card({ content }) { import Card from './Card';
return ( function App() {
<div className="card"> return (
<h2>Card Title</h2> <Card content={<p>This is some custom
<div className="card-content"> <strong>JSX</strong> content!</p>} />
{content} );
</div> }
);
Output: in browser:
}
export default Card;
73 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
• Inside the component you can use props as any regular JavaScript variable.
• You can render conditionally, or you even pass down props to other components.
74 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
• You can define default values for your props by assigning to the special defaultProps property:
75 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
// Render
<HelloOptional />
(OR)
// Render
76 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
• The default Props is used to ensure that this.props.name will have a value if it was not specified by
• The propTypes typechecking happens after default Props are resolved, so typechecking will also
77 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
• If you dynamically construct the props of a component, you might hold the props of the component inside
• The property names inside of the spread object have to correspond to the prop names.
78 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
• Passing children as props is useful when we render child components dynamically. In this scenario,
• Parent component doesn’t need to “know” what’s being rendered inside of it.
• You can think of a component with a children prop as having a “hole” that can be “filled in” by its parent
• When passing children as props, the contents of a JSX component tag body are passed to the
component as props.children.
79 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
margin: 16px; }
.card-header { }
background-color: #3498db; }
80 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
</div> </div>
); );
}; }
81 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
• As your app grows, you can catch a lot of bugs with typechecking.
• To run typechecking on the props for a component, you can assign the special propTypes property:
82 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props
• PropTypes exports a range of validators that can be used to make sure the data you receive is
• When an invalid value is provided for a prop, a warning will be shown in the JavaScript console.
83 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
State in React
• The state is an updatable structure that is used to contain data or information about the component.
• The state in a component is a plain java script object that can change over time.
• The change in state can happen as a response to user action or system event.
• It is the heart of the react component which determines the behavior of the component and how it will
render.
• They are also responsible for making a component dynamic and interactive.
• It is like a JS variable, the difference is while a “normal” variable “disappears” when their function exits,
State in React
• The state data is a private object and is used within components inside a class.
• When the state object changes, the component re-renders. i.e It calls render() method by itself.
86 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
State in React
87 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
Defining state
• To define a state, you have to first declare a default set of values for defining the component's initial
state.
• To do this, add a class constructor which assigns an initial state using this.state.
• To set the state, it is required to call the super() method in the constructor.
• It is because this.state is uninitialized before the super() method has been called.
• State of a component should prevail throughout the lifetime; thus, we must first have some initial state.
88 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
89 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
Update state
• The correct usage of State implicates that one does not apply changes directly to the state variable,
since this won’t be considered a change by React.
• Instead, we should go through this using setState() which is the function that schedules updates to
state objects.
• setState() does not always immediately update the component. It may batch or defer the update until
later.
• This makes reading this.state right after calling setState() a potential pitfall.
90 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
91 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
Callback function
• As a matter of fact, setState() is asynchronous ; One can’t expect to call setState() on one line and
• The reason is that setState() is a mere request to update state rather than an immediate command to
update it.
• To solve this, we can use setState() callback function, which will be guaranteed to fire after the update
92 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
checkAge = () => {
const { age } = this.state;
if (age !== 0 && age >= 21) {
// Make API call to /beer
} else {
// Throw error 404, beer not found
}
};
93 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
• This is most often used when you want to check or make use of previous state before updating any
values.
• This can be safer than using an object argument where multiple calls to setState() are used
94 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
React Hooks
• First released in October of 2018, the React hook APIs provide an alternative to writing class-based
components and offer an alternative approach to state management and lifecycle methods.
• Hooks bring the abilities to functional components(“hook into”) like React local state, effects and
context.
• Better defaults;
95 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
React Hooks
• With React Hooks, developers get the power to use functional components for almost everything they
need to do from just rendering UI to also handling state and logic — which is pretty neat.
• Hook is backward compatible with the code it's replacing and can live side by side with it.
• Hooks work together with existing code, so they can easily be adopted into a codebase.
• Rules of Hooks:
• Make sure to not use Hooks inside loops, conditions, or nested functions; i.e use only at top
level which ensures that Hooks are called in the same order each time a components renders.
• Only use Hooks from inside React Functions not from regular javascript functions
96 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
• There are 10 in-built hooks that was shipped with React 16.8 but the basic (commonly used) hooks
include:
• useState()
• useEffect()
• useContext()
• useReducer()
• useRef()
97 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
useState Hook
• The useState() hook allows React developers to update, handle and manipulate state inside functional
• The useState() hook receives an initial state as an argument and then returns, by making use of array
destructuring in JavaScript, the two variables in the array can be named what.
• The first variable is the actual state, while the second variable is a function that is meant for updating
Destructuring: It’s a JavaScript feature that allows us to extract multiple pieces of data from an
array or object and assign them to their own variables.
98 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
useState Hook
• To use the useState Hook, we first need to import it into our component.
Syntax:
import {useState} from “react”;
• Initialize useState
99 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
function MyComponent() {
const [count, setCount] = useState(0);
useState - Example
101 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
useState Hook
• The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any
combination of these!
• Invoking the state updater function setState(newState) with the new value updates the state.
• Alternatively, you can invoke the state updater with a callback setState(prev => next), which returns the
• After the state updater is called, React makes sure to re-render the component so that the new state
becomes actual.
102 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
103 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks
function App() {
return (
<div className="App">
<CarUpdate />
</div>
);
}
App.js
104 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State
Props Vs States
PROPS STATE
The Data is passed from one component to The Data is passed within the component
another. only.
Props are used to communicate between States can be used for rendering dynamic
106 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
React Lifecycle
Lifecycle
• Lifecycle methods are series of events that happen throughout the birth, growth, and death of a React
component.
107 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
• Each React lifecycle phase has several lifecycle methods that you can override to run code at specified
• The lifecycle methods provide entry points to take over any of these steps.
• Any method that begins with componentWill means you access it before the event occurs and any
method prepended with componentDid means you capture it after the event occurs.
108 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Lifecycle methods
109 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Lifecycle: Mounting
• Mounting is the phase of the component lifecycle when the initialization of the component is
completed, and the component is mounted on the DOM and rendered for the first time on the webpage.
• React has four built-in methods that gets called, in this order, when mounting a component:
– constructor()
– getDerivedStateFromProps()
– render()
– componentDidMount()
• The render() method is required and will always be called, the others are optional and will be called if you
define them.
110 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Mounting: constructor()
• The constructor() is the very first method called as the component is “brought to life.”
• The constructor method is called before the component is mounted to the DOM.
• Its primary use is to initialize state and .bind(this) for the component’s methods.
• In most cases, you would initialize state and bind event handlers' methods within the constructor method.
• Constructor is the only place where you should assign this.state directly. In all other methods, you need
111 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
112 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Mounting: componentWillMount()
• This method is executed right before a component is added to the DOM / render(). It is generally
recommended that you use the constructor, but this method is still included in the API mostly for
backward compatibility.
• You should avoid calling any functions that cause side effects in this method as setState won’t trigger a
• Note that this is also the only lifecycle method called on the server.
113 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Message.js
114 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
115 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Mounting : getDerivedStateFromProps()
• The getDerivedStateFromProps() method is called every time when a component is rendering the
• It can be used to change state when certain props change, and this is the natural place to set the state
• It takes state as an argument and returns an object with changes to the state.
• The following example starts with the favorite color being "red", but the getDerivedStateFromProps()
116 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
117 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Mounting: render()
• After the static getDerivedStateFromProps() method is called, the next lifecycle method in line is the
render() method
• If you want to render elements to the DOM, — e.g., returning some JSX — the render method is where
• You could also return plain strings, numbers, array, Boolean and so on.
• An important thing to note about the render method is that the render function should be pure i.e do
118 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
119 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Mounting : render()
• The render() method is required, and is the method that outputs the HTML to the DOM.
• If you don't want to render anything, you can return a null or false value.
120 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Mounting : componentDidMount()
tree).
• If you need to load data from a remote endpoint, this is a good place to instantiate the network
request.
• It will trigger an extra rendering, but it will happen before the browser updates the screen.
121 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Mounting : componentDidMount()
• This guarantees that even though the render() will be called twice in this case, the user won’t see the
intermediate state.
• Use this pattern with caution because it often causes performance issues.
• In most cases, you should be able to assign the initial state in the constructor() instead.
• It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM
122 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
App.js
124 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Lifecycle: Updating
• This phase of the component lifecycle is triggered as soon as any changes are found in terms of state
or props that allow the DOM to be re-rendered again and again to update the DOM elements.
• React has five built-in methods that gets called, in this order, when a component is updated:
• shouldComponentUpdate()
• render()
• getSnapshotBeforeUpdate()
• componentDidUpdate()
• The render() method is required and will always be called, the others are optional and will be called if
you define them.
125 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Updating: shouldComponentUpdate
• In most cases, you’ll want a component to re-render when state or props changes. However, you do have
control over this behavior.
• If this method returns true, the component will update. Otherwise, the component will skip the updating.
• By default, every state or props update re-render the page, but this may not always be the desired
outcome, sometimes it is desired that updating the page will not be repainted.
• The shouldComponentUpdate() Function fulfills the requirement by letting React know whether the
component’s output will be affected by the update or not.
• If returned false, then the subsequent steps of rendering will not be carried out.
126 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Updating: getSnapshotBeforeUpdate()
• The getSnapshotBeforeUpdatelifecycle method stores the previous values of the state after the DOM is
updated.
• The value queried from the DOM in getSnapshotBeforeUpdate refers to the value just before the DOM is
• If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate()
127 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
128 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
129 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Updating: componentDidUpdate()
• This might happen if new props have been provided by a parent component or an internal state has been
changed.
• The componentDidUpdate gets called after a render, which means that we can access DOM nodes in it.
• It can also access new props and state with this.props and this.state
130 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Updating: componentDidUpdate()
• When you need to access underlying DOM nodes of React components you can use this method.
• Using DOM nodes we can get our component's position and dimensions, or initialize an animation.
We can also pass the underlying DOM node to 3rd party non-React libraries that manipulate DOM.
• When you need to request data from a server or remote API due to changes in component’s props also
131 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Lifecycle - Unmounting
• The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React
• It's possible for a specific component to be removed from the DOM after completion of an operation.
• React has only one built-in method that gets called when a component is unmounted:
• componentWillUnmount()
132 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Unmounting: componentWillUnmount()
• This is the ideal place to perform any necessary cleanup such as clearing up timers, cancelling
133 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
Container(Parent) Component:
134 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
135 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle
• Header component is shown before the button is clicked i.e. before it is unmounted as shown below on
left side:
• Once the button is clicked i.e. the header component is unmounted, the component will be removed as
shown above on right side.
136 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Event Handling
137 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
React Event Handling
Event Handling
• Some things on the screen update in response to user input. For example, clicking an image gallery
switches the active image.
• In React, data that changes over time is called state. You can add state to any component, and update it
as needed.
• Event handlers are your own functions that will be triggered in response to user interactions like clicking,
hovering, focusing on form inputs, and so on.
• Event handlers are defined inside a component, so they can access props. You can declare an event
handler in a parent and pass it as a prop to a child.
Event Handling
To add an event handler, you will first define a function and then pass it as a prop to the appropriate JSX
tag.
– Have names that start with handle, followed by the name of the event.
export default function Button() { <button onClick={function handleClick() {
function handleClick() { alert('You clicked me!');
2
alert('You clicked me!'); }}></button>
}
<button onClick={() => {
return (
alert('You clicked me!');
<button onClick={handleClick}> Click me </button> 3
}}></button>
);
1
}
140 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
JS Local storage
141 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
JS Local storage
• Auth tokens
• Cart items
• Form data
142 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
JS Local storage
// Later
const storedUser = JSON.parse(localStorage.getItem('user'));
- Removing or Clearing
localStorage.removeItem('name');
localStorage.clear(); // clears all localStorage
143 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Lifting state up
144 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
Lifting state up
Lifting state up
• When two sibling components need to share or sync data, you "lift" the state to their closest common
parent so that both children can access or modify that shared state via props.
145 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Lifting state up
• -
import React, { useState } from 'react';
// Child 1 - Input
function NumberInput({ value, onChange }) {
return (
<input
type="number"
value={value}
onChange={(e) => onChange(Number(e.target.value))}
/>
);
}
146 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Lifting state up
// Child 2 - Display
function EvenOddDisplay({ value }) { • -df Output:
return <p>{value} is {value % 2 === 0 ? 'Even' : 'Odd'}</p>;
}
// Parent
function NumberApp() {
const [number, setNumber] = useState(0); // Shared state
return (
<div>
<NumberInput value={number} onChange={setNumber} />
<EvenOddDisplay value={number} />
</div>
);
}
export default NumberApp;
147 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Composition and
Inheritance
Please download pictures in
suitable size here and insert them
by clicking the symbol above.
148 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
Composition and Inheritance
• Composition vs. Inheritance in React, because React encourages composition over inheritance as its
• Composition means building components out of other components—like nesting or passing components
as children or props.
149 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Composition and Inheritance
• React doesn’t use inheritance between components like class-based OOP does. It avoids component
inheritance because:
150 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Composition and Inheritance
151 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Fetch API
152 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
Fetch API
Fetch API
• The Fetch API in React (or any modern JavaScript environment) is used to make HTTP requests to
servers — for example, to retrieve data from a backend API or submit form data.
• In React, you'll typically use it within your components to interact with backend services or external data
sources.
• Here’s a basic example of how to use the Fetch API in a React component to fetch data from an API and
display it:
153 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Fetch API
Fetch API
function Fetchdemo() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then(
(data) => {
setData(data);
},
154 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Fetch API
Fetch API
(error) => {
console.log(error); • -df Output:
}
);
}, [ ]);
return (
<div>
<h1>React AJAX call</h1>
<ul>
{data.map((item) => (
<li key={item.id}>
{item.name} <br />
{item.email}
</li>
))}
</ul>
</div>
);
}
155 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
THANK YOU