0% found this document useful (0 votes)
4 views156 pages

Unit IV-Advanced Client Side Programming

The document outlines a mission to bridge the digital skills gap for over 10 million young professionals by training them in full stack web development, specifically focusing on advanced client-side programming with React JS. It covers the fundamentals of React, including its features, component-based architecture, and the use of JSX for building user interfaces. Additionally, it provides practical guidance on setting up a React environment and creating components for web applications.

Uploaded by

SUGUMARAN - BCA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views156 pages

Unit IV-Advanced Client Side Programming

The document outlines a mission to bridge the digital skills gap for over 10 million young professionals by training them in full stack web development, specifically focusing on advanced client-side programming with React JS. It covers the fundamentals of React, including its features, component-based architecture, and the use of JSX for building user interfaces. Additionally, it provides practical guidance on setting up a React environment and creating components for web applications.

Uploaded by

SUGUMARAN - BCA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 156

We are on a mission to address the digital

skills gap for 10 Million+ young professionals,


train and empower them to forge a career
path into future tech
MCA4201- FULL STACK WEB DEVELOPMENT
UNIT IV - ADVANCED CLIENT SIDE PROGRAMMING
Advanced client side programming

Agenda

• React JS:ReactDOM

• JSX – Components

• Properties Fetch API - State and Lifecycle JS

• Local storage

• Events

• Lifting State Up - Composition and Inheritance

3 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


React JS

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

4 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


Getting Started with React

Introduction

● React is a front-end JavaScript library.

● React was developed by the Facebook Software Engineer Jordan Walke.

● React is also known as React.js or ReactJS.

● React is a tool for building UI components.

● Initial release to the Public (version 0.3.0) was in July 2013.

● React.JS was first used in 2011 for Facebook's Newsfeed feature.

5 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


Getting Started with React

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,

powering Facebook and Instagram among countless other applications.

• Its primary goal is to make it easy to reason about an interface and its state at any point in time, by

dividing the UI into a collection of components.

• 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

reloading complete DOM every time.

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.

• React allows us to write components using a domain-specific language called JSX.

• 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

Settings React environment

● Create React application with the following command, (application name- mycounterapp)

npx create-react-app mycounterapp

• Change working directory to mycounterapp using,

cd mycounterapp

• Then start the npm using,

npm start

9 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


Getting Started with React

Settings React environment

-You will get following screen

10 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


Getting Started with React

Setting up a React Environment


• Next, open the project on Code editor. Our project's default structure looks like as below image.

In React application, there are several files and folders in the root

directory. Some of them are as follows:

• node_modules: It contains the React library and any other third-

party libraries needed.

• public: It holds the public assets of the application. It contains the

index.html where React will mount the application by default on the

<div id="root"></div> element.

11 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React

Setting up a React Environment

• 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

other place rather than the top-level package.

• package.json: It holds various metadata required for the project. It gives information to npm, which

allows to identify the project as well as handle the project’s dependencies.

• README.md: It provides the documentation to read about React topics.

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.

• Following code shows the use of ReactDOM.

import React from 'react';


import ReactDOM from 'react-dom/client';
import App from './App';

// Modern React (v18+)

const root = ReactDOM.createRoot(document.getElementById('root’));

root.render(<App />);

13 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React

React- Hello world using direct HTML

- index.js

import React from 'react';


import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

14 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


Getting Started with React

Modifying the react application

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;

15 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


Getting Started with React

React Features

• Currently, ReactJS gaining quick popularity as the best JavaScript framework among web
developers.

• It is playing an essential role in the front-end ecosystem.

• The important features of ReactJS are as following:

● JSX

● Components

● One-way Data Binding

● Virtual DOM

● Simplicity

● Performance

16 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React

React Features

JSX

• JSX stands for JavaScript XML.

• It is a JavaScript syntax extension.

• Its an XML or HTML like syntax used by ReactJS.

• This syntax is processed into JavaScript calls of ReactJS.

• It extends the ES6 so that HTML like text can co-exist with JavaScript react code.

• It is not necessary to use JSX, but it is recommended to use in ReactJS.

17 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React

React Features

Components

• ReactJS is all about 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

One-way Data Binding

• 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.

• If the data flow is in another direction, then it requires additional features.

• 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

that leads to increase efficiency.

19 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React

React Features

Virtual DOM

• A virtual DOM object is a representation of the original DOM object.

• It works on a one-way data binding.

• 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.

• This makes the application faster, and there is no wastage of memory.

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.

• This makes it simple to use and learn.

21 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Getting Started with React

React Features

Performance

• ReactJS is known to be a great performer.

• This feature makes it much better than other frameworks out there today.

• The reason behind this is that it manages a virtual DOM.

• The DOM is a cross-platform and programming API which deals with HTML, XML or XHTML.

• The DOM exists entirely in memory.

• 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

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

23 MCA4201- FULL STACK WEB DEVELOPMENT |© 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() {

return <h2>Happy Birthday..!</h2>;

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:

– < Greetings />

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Greetings />);

25 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI

Components in Components

• We can refer one component inside of another component.

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() {

return <h2>Happy Birthday..!</h2>;

export default Greetings; Greetings.js

import Greetings from './Greetings.js'; To import Greetings.js from another file

27 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI

Understanding Your UI as a Tree

• Your React app is taking shape with many components being nested within each other.

• React, and many other UI libraries, model UI as a tree.

• 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

The Render Tree

• A major feature of components is the ability to compose components of other components.

• 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

The Render Tree- example

•//Filename:
- App.js <div>

import React from 'react'; <Header />

import Header from './Header'; <Main />

import Main from './Main'; <Footer />

import Footer from './Footer'; </div>

function App() { );

return ( }

export default App;

31 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI

The Render Tree

•//Filename:
- Header.js

import React from 'react';

function Header() {

return <h1>Welcome to My Website</h1>;

}export default Header;

32 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI

The Render Tree

•// filename:
- Main.js <main>

import React from 'react'; <Sidebar />

import Sidebar from './Sidebar'; <Content />

import Content from './Content'; </main>

function Main() { );

return ( }

export default Main;

33 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI

The Render Tree

•// filename:
- Sidebar.js // filename: Content.js

import React from 'react'; import React from 'react';

function Sidebar() {

return <aside>This is the sidebar.</aside>; function Content() {

} return <section>This is the main


content.</section>;
export default Sidebar;
}

export default Content;

34 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI

The Render Tree

•// filename
- : Footer.js

import React from 'react';

function Footer() {

return <footer>© 2025 My Website</footer>;

export default Footer;

35 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Describing the UI

The Render Tree

• 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

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

37 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


React JSX

What is JSX?

• Javascript Syntax Extension (JSX), is a JavaScript extension developed and popularized by

the React framework that allows you to structure the rendering of elements.

• It essentially makes it easier to write HTML code in React .

• 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

and logic together instead of having both in same files.

• 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.

• It is type-safe, and most of the errors can be found at compilation time.

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

any createElement() or appendChild() methods.

• JSX converts HTML tags into react elements.

• 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

React with and without JSX

• React can be written with JSX or without 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

down to under the hood.

41 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX

React with and without JSX

//Without JSX //With JSX

import React from 'react'; import React from 'react';

function App() { function App() {


return React.createElement( return (
'div', <div>
null, <h1>Hello</h1>
React.createElement('h1', null, 'Hello'), <p>Welcome to React</p>
React.createElement('p', null, 'Welcome to React') </div>
); );
} }

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

React with JSX for a block of HTML

//With JSX Inserting a Large Block of HTML


import React, { Component } from 'react';

const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);

class App extends Component{


render(){
return(
myElement
);
}
}
export default App;

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.

• Everything inside it will be managed by React DOM.

• To render a React element, first pass the DOM element to ReactDOM.createRoot(), then pass the

React element to root.render()

• 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

Nested Elements in 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

• With JSX you can write expressions inside curly braces { }.

• The expression can be a React variable, or property, or any other valid JavaScript expression.

• JSX will execute the expression and return the result.

import React from "react"; function App (){


return (
function formatName(user) { <div>
return user.firstName + " " + user.lastName; <h1>Hello, {formatName(user)}!</h1>
} <h2> Simple Expression : 4 x 4 = {4 * 4} </h2>
const user = { </div>
firstName: "Harper", );
lastName: "Perez", }
}; export default App;

46 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX

Embedding JavaScript in JSX

• JavaScript expressions may be embedded within JSX expressions.

• The embedded JavaScript expression must be wrapped in { }.

import React, { Component } from "react";


class App extends Component {
render() {
var cTime = new Date().toTimeString();
return (
<div>
<h1>
current time is = {cTime}
</h1>
</div>
);
}
}
export default App;
47 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

• Close all the tags.


• JSX requires tags to be explicitly closed: self-closing tags like <img> must become <img />, and wrapping tags
like <li>oranges must be written as <li>oranges</li>

• camelCase all most of the things!


• JSX uses camelCase naming convention for attributes rather than standard naming convention of HTML such as
a class in HTML becomes className in JSX because the class is the reserved keyword in JavaScript.

• 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 Custom Attributes

//jsx

function App() {

return <div className="my-box" data-id="123" data-my-custom="hello">Hello</div>;

// Rendered HTML

return <div class="my-box" data-id="123" data-my-custom="hello">Hello</div>;

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

import React, { Component } from 'react';


class App extends Component{
render(){
return(
<div>
<h1>Welcome</h1>
{/* This is a comment in JSX */}
</div>
);
}
}
export default App;

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

also increased and evolved over the years.

• Three common ways:

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.

• This is similar in React.

• We can add inline styles to any React component we want to render.

• 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

JSX Styling – inline Example

import React from "react";

function App() {

return (

<div>

<h1 style={{ fontSize: 20, fontFamily: "Courier", color: "red" }}>

Welcome to React JSX

</h1>

</div>

);

export default App;

54 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React JSX

JSX Styling

2. Creating a style object variable

• 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

JSX Styling – style object Example

import React from 'react';


function App () {
var myStyle = {
fontSize: 20,
fontFamily: 'Courier',
color: 'red'
}
return (
<div>
<h1 style = {myStyle}>Welcome to React JSX</h1>
</div>
);
}
export default App;

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

import it in your application.

• Create a new file called "App.css" and insert some CSS code in it:

h1{ fontSize: 20, fontFamily: "Courier", color: "red" }

• 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

JSX Styling – stylesheet Example

Import the stylesheet in your application

import React from 'react';

import "./styles.css";

function App (){

return (

<div>

<h1>Welcome to React JSX</h1>

</div>

);

export default App;

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

JSX Styling – css module Example

Import the stylesheet in your component

import React from 'react';


import styles from './my-style.module.css';
function App() {
return (
<div>
<h1 className = {styles.bigblue}>Welcome to React JSX</h1>
</div>
);
}
export default App;

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.

• To do so, in your react project install ‘sass’ module using npm.

• Create a scss file as css module

– Ex: MyComponent.module.css

• Then import that file in your required pages.

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

JSX Styling – SASS Example

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.

64 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0


React Component’s Props

props

• React components use props to communicate with each other.

• Props are arguments passed into React components.

• Props are passed to components via HTML attributes.

• Props stands for properties. They are “Read-only” elements.

• They are like function arguments in JavaScript and attributes in HTML.

function Car(props) {

return <h2>I am a { props.brand } car!</h2>;

const myElement = <Car brand="Ford" />;

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

• -

//file name: Greetings.js


import React from 'react';

//Output
function Greeting(props) { Hello, Alice!
return <h1>Hello, {props.name}!</h1>; Hello, Bob!
}

export default Greeting;

67 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Multiple props

• React components can accept more than one props.

function Message({ greet, who }) {

return <div>{greet}, {who}!</div>;

// Render

<Message greet="Welcome" who="Aliens" />

// Output

Welcome, Aliens!

68 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Values of Props

• In most of the cases, the values of props were strings.

• 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">

Component will be as follows:


function MyComponent({ prop }) {
return <div> Prop value: {prop}</div>;
}
69 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Values of Props

Template literals with variables:


<MyComponent prop={`My String Value ${myVariable}`}>
Number literals:
<MyComponent prop={42} />
Boolean literals:
<MyComponent prop={false} />
Plain object literals:
<MyComponent prop={{ property: 'Value' }} />
Array literals:
<MyComponent prop={['Item 1', 'Item 2']} />
JSX:
<MyComponent prop={<Message who="Joker" />} />
Variables having any kind of value:
<MyComponent prop={myVariable} />

70 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Passing data to props: As variable

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

Passing data to props: As Objects

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> }

</div> export default App;

);
Output: in browser:
}
export default Card;

73 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Passing down 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.

function HelloPeople({ persons }) {


return (
<div>
{persons.map((person, index) => {
function Hello(props) {
return <Hello who={person} key={index} />;
})} return <div>Hello, {props.who}!</div>;
</div>
}
);
}
// Render
<HelloPeople persons={[Smith’, John']} />

74 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Default Prop Values

• You can define default values for your props by assigning to the special defaultProps property:

class Greeting extends React.Component {


render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}

// Specifies the default values for props:


Greeting.defaultProps = { name: 'Stranger’ };

// Renders "Hello, Stranger":


const root = ReactDOM.createRoot(document.getElementById('example'));
root.render(<Greeting />);

75 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Default Prop – Using functional Component

function HelloOptional({ who = 'Unknown' }) {

return <div>Hello, {who}!</div>;

// Render

<HelloOptional />

(OR)

// Render

<HelloOptional who="Batman" />

76 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Default Prop Values

• The default Props is used to ensure that this.props.name will have a value if it was not specified by

the parent component.

• The propTypes typechecking happens after default Props are resolved, so typechecking will also

apply to the default Props.

77 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Props spread syntax

• If you dynamically construct the props of a component, you might hold the props of the component inside

of a plain JavaScript object.

• The property names inside of the spread object have to correspond to the prop names.

function Message({ greet, who }) {


return <div>{greet}, {who}!</div>;
}
const greetUser = { greet: 'Hi', who: ‘Smith’ };
// Render
<Message {...greetUser} />

78 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Passing JSX as children

• Passing children as props is useful when we render child components dynamically. In this scenario,

we don't know the content to render ahead of time.

• 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

components with arbitrary JSX.

• 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

Passing JSX as children

//Card.scss color: #fff;

card { padding: 8px;

border: 1px solid #ccc; border-top-left-radius: 8px;

border-radius: 8px; border-top-right-radius: 8px;

margin: 16px; }

padding: 16px; .card-content {

box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); margin-top: 8px;

.card-header { }

background-color: #3498db; }

80 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Passing JSX as children

import React from "react"; import React from "react";


import "./Card.scss"; import Card from "./Card";
const Card = ({ title, children }) => { function App() {
return ( return (
<div className="card"> <div className="App">
<div className="card-header"> <Card title="Card Title">
<h3>{title}</h3> <p>This is the content of the card.</p>
</div> <button>Click me</button>

<div className="card-content">{children}</div> </Card>

</div> </div>

); );

}; }

export default Card; export default App;

81 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Typechecking With Prop Types

• As your app grows, you can catch a lot of bugs with typechecking.

• React has some built-in typechecking abilities.

• To run typechecking on the props for a component, you can assign the special propTypes property:

import PropTypes from 'prop-types';

class Greeting extends React.Component {


render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}

Greeting.propTypes = { name: PropTypes.string };

82 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Component’s Props

Typechecking With Prop Types

• PropTypes exports a range of validators that can be used to make sure the data you receive is

valid. In this example, we’re using PropTypes.string.

• When an invalid value is provided for a prop, a warning will be shown in the JavaScript console.

• For performance reasons, propTypes is only checked in development mode.

83 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

84 MCA4201- FULL STACK WEB DEVELOPMENT |© 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,

the state variables are preserved by React.


85 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State

State in React

• The state is a built-in React object that is used to contain data.

• 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.

• The state object can contain as many properties as it requires.

• A component with the state is known as stateful components.

86 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State

State in React

• There are two primary ways to define state in React components:

• Using class properties (for class components)

• Using the useState Hook (for functional components)

Using class properties:

Class MyClass extends React.Component {


constructor(props) {
super(props);
this.state = { attribute : "value" };
}
}

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.

• The 'this.state' property can be rendered inside render() method.

• 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

State – Example- Using class properties

class House extends React.Component {


constructor(props) {
super(props);
this.state = {
street : “Cracker St 108“,
type : “Family House”,
color : “White”,
yearOfConstruction : 1999
};
}
render() {
return (
<div> <h1>Example state </h1> </div>
);
}

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.

setState({ stateName : updatedStateValue })

• State should never be updated explicitly.

90 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State

setState – Example - Using class properties

class Bike extends React.Component { <h2>My {this.state.make}</h2>


constructor(props) {
super(props); <p>
this.state = { It is a {this.state.color}
make: "Yamaha", {this.state.model}.
model: "R15", </p>
color: "blue",
}; <button type="button" onClick={this.changeBikeColor}>
} Change color
changeBikeColor = () => { </button>
this.setState({ color: "black" }); </div>
}; );
render() { }
return ( }
<div>

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

assume the state has been updated on the next line.

• 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

has been applied.

92 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React State

Callback function – Example

// this.checkAge is passed as the callback to setState


updateAge = (value) => {
this.setState({ age: value}, this.checkAge);
};

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

setState with functional parameters

• 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

• Multiple calls may be batched together by React and executed at once.


function addAnotherPizza(state, props) {
return {
pizza: state.pizza + 1,
}
}
this.setState(addAnotherPizza);

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.

• They allow React Developers to enjoy the following benefits:

• Improved code reuse;

• Better code composition;

• Better defaults;

• Sharing non-visual logic with the use of custom hooks;

• Flexibility in moving up and down the components tree.

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.

• It does not work inside classes.

• 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

• Hooks can call other Hooks

96 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks

Basic 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()

These are the most commonly used hooks.

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

components without needing to convert it to a class component.

• 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

the state by providing a new state.

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

• We initialize our state by calling useState in our function component.

• useState accepts an initial state and returns two values:

• The current state.

• A function that updates the state.

99 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks

State – Example- Using the useState Hook (for functional components)

import React, { useState } from 'react’;

function MyComponent() {
const [count, setCount] = useState(0);

const increment = () => {


setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
100 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks

useState - Example

import React, { useState } from "react"; import React from "react";


import IncreaseAge from "./ IncreaseAge ";
export default function IncreaseAge(props) { function App() {
const [age, setAge] = useState(19); return (
const handleClick = () => setAge(age + 1); <div className="App">
< IncreaseAge />
return ( </div>
<div> );
I am {age} years old. }
<div> export default App; App.js
<button onClick={handleClick}>Increase my Age...</button>
</div>
</div>
);
} IncreaseAge.js

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!

• We could create multiple state Hooks to track individual values.

• 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

new state based on previous.

• 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

Updating State Objects – Example

import React, { useState } from "react"; return (


<>
export default function CarUpdate() { <h1>My {car.brand}</h1>
const [car, setCar] = useState({ <p>
brand: "Ford", It is a {car.color} {car.model} from {car.year}.
model: "Mustang", </p>
year: "1964", <button type="button" onClick={updateColor}>
color: "red", Change Color
}); </button>
</>
const updateColor = () => { );
setCar((previousState) => { }
return { ...previousState, color: "blue" };
});
}; CarUpdate.js

103 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Hooks

Updating State Objects – Example

import React from "react";


import CarUpdate from "./CarUpdate";

function App() {
return (
<div className="App">
<CarUpdate />
</div>
);
}

export default App;

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.

It is Immutable (cannot be modified). It is Mutable ( can be modified).

State can be used only with the state


Props can be used with state and functional
components/class component (Before
components.
16.0).

Props are read-only. State is both read and write.

Props are used to communicate between States can be used for rendering dynamic

components. changes with the component.

105 React | © SmartCliff | Internal | Version 1.0


React Lifecycle

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

106 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
React Lifecycle

Lifecycle

• React component lifecycle as the “lifetime” of a component.

• Lifecycle methods are series of events that happen throughout the birth, growth, and death of a React

component.

• In React, components go through a lifecycle of events:

• Mounting (adding nodes to the DOM)

• Updating (altering existing nodes in the DOM)

• Unmounting (removing nodes from the DOM)

• Error handling (verifying that your code works and is bug-free)

107 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

React lifecycle methods

• Each React lifecycle phase has several lifecycle methods that you can override to run code at specified

times during the process.

• These are popularly known as component lifecycle methods.

• 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

to use this.setState() instead.

111 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Mounting: constructor() – Example

import React from 'react';


import ReactDOM from 'react-dom/client';

class Header extends React.Component {


constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Header />);

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

change and there is no DOM to interact with.

• 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

Mounting: componentWillMount() - Example

import React from "react";

class Message extends React.Component {


constructor() {
super();
this.state = {
message: "This is initial message",
};
}
componentWillMount() {
this.setState({ message: "This is an updated message" });
}

Message.js

114 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Mounting: componentWillMount() - Example

render() { import React from "react"; App.js


return ( import "./App.css";
<div> import Message from "./Message";
<p>Update the state</p> function App() {
<hr /> return (
{this.state.message} <div className="App">
</div> <Message />
); </div>
} );
} }

export default Message;

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

element(s) in the DOM.

• It can be used to change state when certain props change, and 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.

• While it is a rarely used lifecycle method, it comes in handy in certain scenarios.

• The following example starts with the favorite color being "red", but the getDerivedStateFromProps()

method updates the favorite color based on the favcol attribute.

116 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Mounting : getDerivedStateFromProps() Example

import React from 'react';


import ReactDOM from 'react-dom/client';

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>
);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Header favcol="yellow"/>);

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 would write this.

• 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

not attempt to use setState or interact with the external APIs.

118 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Mounting : render() Example

import React from 'react';


import ReactDOM from 'react-dom/client';

class Header extends React.Component {


render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Header />);

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.

• This method is defined in every component.

• It is responsible for returning a single root HTML node element.

• 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()

• componentDidMount() is invoked immediately after a component is mounted (inserted into the

tree).

• Initialization that requires DOM nodes should go here.

• If you need to load data from a remote endpoint, this is a good place to instantiate the network

request.

• This method is a good place to set up any API call.

• You may call setState() immediately in componentDidMount().

• 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

node before rendering something that depends on its size or position.

122 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Mounting : componentDidMount() Example

import React, { Component } from "react";

class WallStreet extends Component { componentDidMount() {


constructor(props) { this.getData();
super(props); }
this.state = {
data: "Jordan Belfort", render() {
}; return (
} <div>
<h1>{this.state.data}</h1>
getData() { </div>
setTimeout(() => { );
console.log("Our data is fetched"); }
this.setState({ }
data: "The Wolf of WallStreet",
}); export default WallStreet;
}, 1000);
} WallStreet.js
123 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Mounting : componentDidMount() Example

import React from "react";


import "./App.css"; Page rendered initially on being loaded
import WallStreet from "./WallStreet";
function App() {
return (
<div className="App">
<WallStreet />
</div>
); Page re-rendered after state change
}

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:

• getDerivedStateFromProps() – It is invoked in both mounting and updating phases.

• 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.

• shouldComponentUpdate() is invoked before rendering an already mounted component when new


props or state are being received.

• 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.

• getSnapshotBeforeUpdate() is called right after the render method.

• The value queried from the DOM in getSnapshotBeforeUpdate refers to the value just before the DOM is

updated, even though the render method was previously called.

• The data returned by this method will be passed to ComponentDidUpdate() method.

• If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate()

method, otherwise you will get an error.

127 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Updating: getSnapshotBeforeUpdate() – Example

import React from 'react';


import ReactDOM from 'react-dom/client';

class Header extends React.Component {


constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was "
+ prevState.favoritecolor;
}

128 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Updating: getSnapshotBeforeUpdate() – Example

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>
);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Header />);

129 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Updating: componentDidUpdate()

• componentDidUpdate() method is called when a component got updated.

• 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.

• This function receives previous props and state as parameters.

• 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

you can use this method

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

likes to call it.

• 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()

• The componentWillUnmount() lifecycle method is invoked immediately before a component is

unmounted and destroyed.

• This is the ideal place to perform any necessary cleanup such as clearing up timers, cancelling

network requests, or cleaning up any subscriptions that were created in componentDidMount().

• If a component instance is unmounted, you cannot mount it again.

133 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Unmounting: componentWillUnmount() – Example

Container(Parent) Component:

import React from 'react';


import ReactDOM from 'react-dom/client';

class Container extends React.Component { return (


constructor(props) { <div>
super(props); {myheader}
this.state = {show: true}; <button type="button"
} onClick={this.delHeader}>Delete Header</button>
delHeader = () => { </div>
this.setState({show: false}); );
} }
render() { }
let myheader;
if (this.state.show) {
myheader = <Child />;
};

134 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Unmounting: componentWillUnmount() – Example


Header(Child) Component:

class Child extends React.Component {


componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Container />);

135 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Lifecycle

Unmounting: componentWillUnmount() – Example

• 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

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

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.

• React lets you add event handlers to your JSX.

• 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.

• Built-in components support built-in browser events.

• 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 handlers are the best place for side effects.


138 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Event Handling

Event Handling

export default function App() {


return ( <Button onClick={onUploadImage}>
<Toolbar Upload Image
onPlayMovie={() => alert('Playing!')} </Button>
onUploadImage={() => alert('Uploading!')} </div>
/> );
); }
}
function Button({ onClick, children }) {
function Toolbar({ onPlayMovie, onUploadImage }) { return (
return ( <button onClick={onClick}>
<div> {children}
<Button onClick={onPlayMovie}> </button>
Play Movie );
</Button> }
139 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
React Event Handling

Adding 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.

Event handler functions:

– Are usually defined inside your components.

– 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

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

141 MCA4201- FULL STACK WEB DEVELOPMENT |© Smartcliff | Internal | Version 1.0
JS Local storage

Need for local storage

To persist data across page reloads and browser sessions—like:

• User preferences (dark mode)

• Auth tokens

• Cart items

• Form data

142 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
JS Local storage

Need for local storage

- Storing data in JSON

const user = { id: 1, name: 'Jane' };


localStorage.setItem('user', JSON.stringify(user));

// 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

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

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.

Let's say we have two components:

• One to input a number

• Another to display if the number is even or odd

145 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Lifting state up

Lift state up to the parent- example

• -
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

Lift state up to the parent- example

// 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 and Inheritance

• Composition vs. Inheritance in React, because React encourages composition over inheritance as its

primary code reuse mechanism.

• 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

Composition and Inheritance

• React doesn’t use inheritance between components like class-based OOP does. It avoids component

inheritance because:

• It leads to tight coupling,

• It makes code harder to reuse and test.

• It’s less flexible than composition

150 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Composition and Inheritance

Why React Prefers Composition

• Encourages decoupled, reusable components

• Makes your component tree more predictable.

• Works great with hooks and functional components

151 MCA4201- FULL STACK WEB DEVELOPMENT React | © SmartCliff | Internal | Version 1.0
Fetch API

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

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

import { useState, useEffect } from "react";


import "./App.css"; • -df Output:

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

You might also like