WDF Unit 3 Digital Notes
WDF Unit 3 Digital Notes
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
22IT407
WEB DEVELOPMENT FRAMEWORKS
(Lab Integrated)
Batch / Year / Semester: 2023-2027 / II / 4
4
1. CONTENTS
S.NO. CONTENTS PAGE NO
1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course Outcomes 13
6 CO- PO/PSO Mapping 14
7 Lecture Plan 15
8 Activity Based Learning 16
9 Lecture Notes 18-56
10 Assignment – 1 to 5 57-58
11 Part A Questions & Answers 59-73
12 Part B Questions 74
Supportive Online Certification 75
13
Courses
14 Real time Applications 76-77
15 Contents Beyond the Syllabus 78
16 Assessment Schedule 80
Prescribed Text Books & Reference 81
17
Books
18 Mini Project – 1 to 5 82
5
2. COURSE OBJECTIVES
OBJECTIVES:
6
3. PRE REQUISITES
• Pre-requisite Chart
22IT407
22CS102
-
SOFTWARE DEVELOPMENT PRACTICES
7
4. Syllabus
22IT407 – WEB DEVELOPMENT FRAMEWORKS (Lab Integrated) – L T P C - 3 0 2 4
6
4. Syllabus
2) Develop a Scientific calculator that does following operations
➢ Rounded Value
➢ Area of Circle
➢ Calculating of Sin, Cos and Tan functions
➢ Permiter of a Rectangle
➢ Employ Arrow functions
➢ Employ HOC
UNIT III - REACT COMPONENTS – 9+6
Class vs Functional Components, Lifecycle methods - React Class Based Components
– component DidMount, WillUpdate, shouldupate, didcatchetc - State - UseState,
UseRef, USeEffect, UseHistory Usage and Props(difference, when to use what,
mutable or immutabilty,direction of flow), PropTypes, Auxillary Components,
Controlled and Uncontrolled Components, Component Interaction (Parent to Child and
Child to Parent), Iteration & Conditional Response
List of Exercise/Experiments
1) Create a collection of Customer by using
➢ Weak Map and Map Collection in JS
➢ Show Case the different feature set of the same.
2) Add Login Page, Dash Board Page, Admin Page
➢ Enable React Routing
➢ Add React Protected Route, for authorization
UNIT IV - REACT LIBRARY – I – 9+6
Event Bubbleup - Component Wrapper - Integration of CSS Modules - Forms
Validations(YUP, Formik, Standard), Events Handling, Data Binding - Redux
List of Exercise/Experiments
1) Develop a React application that has User Registration Form w field
level validations, data submission to a rest api end point, boot strap for
responsive.
➢ Use YUP or Formik to implement the same.
4. Syllabus
2) Build a Redux Counter Application
Requirements:
➢ React application with Redux integrated.
➢ A counter with:
➢ Increment button
➢ Decrement button
➢ Reset button
➢ Display the current counter value.
UNIT V - REACT LIBRARY – II – 9+6
Custom Hooks, HTTP - Fetch, Axios, and Context API, Services, Behaviour Subjects -
StateLess, StateFulll and Container Components, Error Handling - Build, Env, CORS, Unit
Testing w React Testing Library - Introduction to react-native - Introduction to StoryBook
List of Exercise/Experiments
1) Employ backend API for Login Page functionality (authentication). Post login,
store the user context (received from the back end server) in browser’s session
storage as objects. And use the same as creds during protected route verification.
➢ On the dashboard page, have a grid of Students. The data has to be bought
from backend api
➢ Employ useref, useeffect & usestate, and useHistory
2) Enable Exception Handling
3) Enable HOC and Aux Components
4) Implement React-Testing Library
5) Basic Context Setup
Objective: Set up a React Context to manage theme (light or dark).
➢ Create a ThemeContext using React.createContext.
➢ Create a provider component ThemeProvider with state to toggle
between "light" and "dark" themes.
➢ Use the context in a functional component to display the current theme.
➢ Add a button to toggle the theme.
4. SYLLABUS
Business Use Case Implementations
3) E-Commerce System
4) Student LMS Management System
TOTAL:45+30=75 PERIODS
TEXTBOOK:
1. David Flanagan, Javascript The Definitive Guide, Paperback, 7th Edition, 2020.
2. David Choi ,Full-Stack React, TypeScript, and Node: Build cloud-ready web
applications using React 17 with Hooks and GraphQL Paperback – Import, 18
December 2020.
3. Mehul Mohan, Advanced Web Development with React Paperback – 1 January
2020.
E-RESOURCES:
1.Parental Website - https://reactjs.org/
2.The Road to Learn React: Your journey to master plain yet pragmatic React.js by
Robin Wieruch
3.Learning React: Functional Web Development with React and Redux by Alex Banks
and Eve Porcello
4. Learning React by KirupaChinnathambi
5. "React Up & Running" by StoyanStefanov
6. https://www.edureka.co/reactjs-redux-certification-training
7. CodePen
8. CodeSandbox (Preferred)
9. Stackblitz
11
4. SYLLABUS
LIST OF EQUIPMENTS:
• NodeJS (v9.11.2)
• Github as code repository
• Visual studio code as IDE
• RTL as unit testing framework
• Responsive design w bootstrap
• ReactJS installation (v17)
• Chrome / FIreFox Browsers (latest)
• Responsive using Media Queries & Bootstrap Material & Antdesign
• Design based Apps.
12
5. Course Outcomes
Course Outcomes with Knowledge Levels:
CO1: Personalize web pages using text formatting, graphics, audio,
and video. - K3
CO2: Hands on knowledge on Rest API , propTypes. - K3
CO3: Able to develop a web application using latest React
Framework – K3
CO4: Apply various React features including functions,
components, and services. – K3
CO5: Able to develop application using ReactJshooks. – K3
CO6: Design and integrate complex web components to enhance
user interface and user experience in React applications. – K5
11
6. CO-PO/PSO Mapping
CO2 3 2 3 1 2 - - - 2 1 - 1 3 3 1
CO3 3 3 3 1 2 - - 1 2 1 - 1 3 3 1
CO4 3 3 3 1 2 - - - 2 1 - 1 3 3 1
CO5 3 3 3 1 2 - - 1 2 1 - 1 3 3 1
CO6 2 3 3 - 3 - - 1 2 2 - 3 3 3 1
CO 2.83 2.83 3.00 1.00 2.00 - - 1.00 2.00 1.17 - 1.33 3.00 3.00 1.00
Correlation Level
1. Slight (Low)
2. Moderate (Medium)
3. Substantial (High) ,
If there is no correlation, put “-“.
12
7. LECTURE PLAN
Sl. Taxono
No. of. Proposed Actual Pertaining Mode of
No Topics my
Periods Date Date CO Delivery
. Level
As per As per
Class vs Functional CO3, MD 1,
1 1 academic academic K3
Components CO4,CO5 MD 4
calendar calendar
As per As per
State - UseState, CO3, MD 1,
4 1 academic academic K3
UseRef, CO4,CO5 MD 4
calendar calendar
USeEffect,UseHisto
ry Usage and
Props(difference, As per As per
CO3, MD 1,
5 when to use what, 1 academic academic K3
CO4,CO5 MD 4
mutable or calendar calendar
immutabilty,
direction of flow)
PropTypes, As per As per
CO3, MD 1,
6 Auxillary 1 academic academic K3
CO4,CO5 MD 4
Components calendar calendar
Controlled and As per As per
CO3, MD 1,
7 Uncontrolled 1 academic academic K3
CO4,CO5 MD 4
Components calendar calendar
Component
As per As per
Interaction (Parent CO3, MD 1,
8 1 academic academic K3
to Child and Child CO4,CO5 MD 4
calendar calendar
to Parent)
Iteration &
As per As per
Conditional CO3, MD 1,
9 1 academic academic K3
Response CO4,CO5 MD 4
calendar calendar
10 As per As per
CO3,
- Lab Exercises 6 academic academic K3 iamneo
CO4,CO5
15 calendar calendar
Common Activities
Check out this live CodePen demo to preview what you will build. Or, explore the
complete code from the GitHub repo of this project.
Lecture Notes
A Component is one of the core building blocks of React. In other words, we can say that
every application you will develop in React will be made up of pieces called components.
Components make the task of building UIs much easier. You can see a UI broken down into
multiple individual pieces called components and work on them independently and merge
them all in a parent component which will be your final UI.
You can see in the below image we have broken down the UI of GeeksforGeeks’s homepage
into individual components.
Components in React basically return a piece of JSX code that tells what should be rendered
on the screen.
Types of components in ReactJS.
In React, we mainly have two types of components:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
In the above syntax, the ComponentName is the name of the user-defined component.
Note: The name of a component should always start with a capital letter. This is done to
differentiate a component tag from HTML tags.
The below example renders a component named Welcome to the Screen:
Open your index.js file from your project directory, and make the given below changes:
src index.js:
ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
❑ Let us see step-wise what is happening in the above example:
❑ We call the ReactDOM.render() as the first parameter.
❑ React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the
result.
❑ Then the ReactDOM efficiently updates the DOM to match with the returned element and
renders that element to the DOM element with id as “root”.
Components let you split the UI into independent, reusable pieces, and think about each
piece in isolation. This page provides an introduction to the idea of components.
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called
“props”) and return React elements describing what should appear on the screen.
Composing Components
Components can refer to other components in their output. This lets us use the same
component abstraction for any level of detail. A button, a form, a dialog, a screen: in React
apps, all those are commonly expressed as components.
For example, we can create an App component that renders Welcome many times:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>; }
function App() {
return ( <div> <Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome
name="Edite" /> </div> ); }
Extracting Components
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar" src={props.author.avatarUrl} alt={props.author.name} />
<div className="UserInfo-name"> {props.author.name} </div>
</div>
<div className="Comment-text"> {props.text} </div>
<div className="Comment-date"> {formatDate(props.date)} </div>
</div> ); }
• The class component is also known as a stateful component because they can hold or
manage local state. It can be explained in the below example.
Example
• In this example, we are creating the list of unordered elements, where we will dynamically
insert StudentName for every object from the data array. Here, we are using ES6 arrow
syntax (=>) which looks much cleaner than the old JavaScript syntax. It helps us to create
our elements with fewer lines of code. It is especially useful when we need to create a list
with a lot of items.
❑ The state is an updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state over time
can happen as a response to user action or system event. A component with the state is
known as stateful components. 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.
❑ A state must be kept as simple as possible. It can be set by using the setState() method
and calling setState() method triggers UI updates. A state represents the component's local
state or information. It can only be accessed or modified inside the component or by the
component directly. To set an initial state before any interaction occurs, we need to use
the getInitialState() method.
❑ For example, if we have five components that need data or information from the state,
then we need to create one container component that will keep the state for all of them.
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.
Example
The below sample code shows how we can create a stateful component using ES6 syntax.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: true };
}
render() {
const bio = this.state.displayBio ? (
<div>
<p><h3>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.</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to REACT CLASS</h1>
{ bio }
</div>
);
}
}
export default App;
• 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.
We can change the component state by using the setState() method and passing a new
state object as the argument. Now, create a new method toggleDisplayBio() in the above
example and bind this keyword to the toggleDisplayBio() method otherwise we can't access
this inside toggleDisplayBio() method.
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
Example
In this example, we are going to add a button to the render() method. Clicking on this
button triggers the toggleDisplayBio() method which displays the desired output.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: false };
console.log('Component this', this);
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
}
toggleDisplayBio(){
this.setState({displayBio: !this.state.displayBio});
}
render() {
return (
<div>
<h1>Welcome to REACT CLASS</h1>
{
this.state.displayBio ? (
<div>
<p><h4>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.</h4></p>
<button onClick={this.toggleDisplayBio}> Show Less </button>
</div>
):(
<div>
<button onClick={this.toggleDisplayBio}> Read More </button>
</div>
)
}
</div>
)
}
} export default App;
3.4 REACT COMPONENT LIFECYCLE METHODS
Mounting
This phase of the component lifecycle is used to call the method when the instance of the
component can be created. It is also called while inserting the component into the HTML
DOM. There are a few methods used in the mounting phase;
constructor()
The constructor() method is called before anything else when the component is initiated, and it
is the natural place to set up the initial state and other initial values. This method is called with
the props as arguments, and you should always start by calling the super (props) before
anything else, this will initiate the parent’s constructor method and allows the component to
inherit methods from its parent (React.Component).
render()
Rendering is a crucial procedure programmer must manage in front end development. The
render() method is the only required method in a class component and is responsible for
describing the view to be rendered to the browser window. It is important to note that this
method is not user callable but is a part of the React Component Lifecycle. Within the lifecycle,
there are a number of scenarios when render is called;
After the React component is first instantiated, following the constructor() call.
After an update to the component’s props
After a setState() call
componentDidMount()
The componentDidMount() method enables us to execute the React code when the component
is already placed in the Document Object Model. All the AJAX requests and the DOM or state
updation should be coded in the componentDidMount() method block. After all the elements of
the page are rendered correctly, this method is called. After the markup is set on the page, this
technique is called by React itself to either fetch the data from an External API or perform some
unique operations which need the JSX elements.
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. The updating phase includes several lifecycle hooks; requests.
getDerivedStateFromProps
This method is invoked right before calling the render method, both on the initial mount and on
subsequent updates. It should return an object to update the state, or null to update nothing.
The method exists for rare use cases where the state depends on changes in props over time.
shouldComponentUpdate ()
The shouldComponentUpdate () method may be used to let React know if a component’s output
is not affected by the current change in state or props. The default behaviour is to re-render on
every state change, and in the vast majority of cases, you should rely on the default behaviour.
componentDidUpdate ()
The componentDidUpdate method is called after the component is updated in the DOM. The
componentDidUpdate lifecycle method is invoked after the getSnapshotBeforeUpdate. As with
the getSnapshotBeforeUpdate method, it receives the previous props and state as arguments.
Whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as the
third argument to the componentDidUpdate method. nnecessary network
getSnapshotBeforeUpdate()
In the getSnapshotBeforeUpdate() method you have access to the props and state before the
update, meaning that even after the update, you can check what values were before the update.
If the getSnapshotBeforeUpdate() method is present, you should also include the
componentDidUpdate() method, otherwise, you will get an error.
Unmounting
The unmounting phase begins when an existing component is removed from the DOM. It
includes a single and important lifecycle hook, componentWillUnmount().
Error Handling
This is one of the most crucial phases of the component, error handling is used to trigger an
action in case of an error during the component rendering. There are two methods used to
manage the errors in the existing component;
ComponentDidCatch()
ComponentDidCatch() was added in React 16 and is used in error boundaries. A component
becomes an error boundary if it defines the componentDidCatch method. In this method,
this.set State can be called and used to catch an unhandled Javascript error in a child
component tree and display a fallback UI instead of the component that crashed. These
errors are caught during rendering, in lifecycle methods, and in constructors of the whole
tree below them.
Static GetDerivedStateFromError()
This is a complete list of lifecycle phases and component lifecycle hooks that trigger based
on each phase and component behaviour. Any of them can be chosen to trigger actions that
are reflected in the DOM. In this article, we shall put our emphasis on
ComponentDidUpdate(), one of the lifecycle methods under the updating stage.
❑ This lifecycle method gets called right after a change in props or a state change has
occurred. 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 you can access
DOM nodes in it. This function receives props and states as parameters. It can also
access new props and state with this.props and this.state. It provides the previous pros
and state values and in this way it allows you to do a comparison of a before and current
snapshot.
❑ Best use-cases of the ComponentDidUpdate() lifecycle;
✓ API calls after specific conditions have been met
✓ DOM manipulation after the component has been rendered.
✓ Update React state or stores like Redux and Mobx after a set of conditions have been
met.
❑ React Lifecycle triggers and events are designed to give developers the opportunity to
make decisions and take appropriate actions. A component goes through a series of
lifecycle events from when it is invoked to when it is destroyed. There are four triggers
that kick off these lifecycle events; Intiatilization, Updating State, Updating Props and
Unmounting. The componentDidUpdate event is triggered whenever there is a state or
props update.
❑ ComponentDidUpdate() has access to three properties, two of which are most often used
more than the third. These are prevProps, prevState and lastly, snapshot, which is used
less often. ComponentDidUpdate() is invoked immediately after updating occurs and is
not called for the initial render. The most common use-case for the componentDidUpdate
() lifecycle method is updating the DOM in response to Prop or State changes.
❑ This updating method is also the best point in the lifecycle to perform an interaction with
a non-React environment like the browser or making HTTP requests. This should be done
as long as you compare the current props to the previous props to avoid u
3.5 REACT STATES
Consider the ticking clock example from one of the previous sections. In Rendering Elements,
we have only learned one way to update the UI. We call root.render() to change the rendered
output:
const root = ReactDOM.createRoot(document.getElementById('root'));
function tick() {
const element = (
<div> <h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div> );
root.render(element);
}
setInterval(tick, 1000);
Hooks are a new addition in React 16.8. They let you use state and other React features
without writing a class.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div> <p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div> );
}
Before we continue, note that Hooks are:
• Completely opt-in. You can try Hooks in a few components without rewriting any existing
code. But you don’t have to learn or use Hooks right now if you don’t want to.
• 100% backwards-compatible. Hooks don’t contain any breaking changes.
• Available now. Hooks are now available with the release of v16.8.0.
• There are no plans to remove classes from React. You can read more about the gradual
adoption strategy for Hooks in the bottom section of this page.
• Hooks don’t replace your knowledge of React concepts. Instead, Hooks provide a more direct
API to the React concepts you already know: props, state, context, refs, and lifecycle.
3.6.1 ) UseState HOOKS
Voting.js
import { useState } from "react";
export function Voting(props) {
const [like, setLike] = useState(0);
const [dislike, setDislike]=useState(0);
return (
<div className="Votes"
style = {like>dislike?{background:"green"}:{background:"yellow"}}>
<h1>{props.brandname}</h1>
<h4>{props.Model}</h4>
name: "OnePlus",
model: "O14",
},
];
return (
<div>
{brands.map((mob) => (
))}
</div>
);
}
export default App;
Here, useState is a Hook (we’ll talk about what this means in a moment). We call it inside a
function component to add some local state to it. React will preserve this state between re-
renders. useState returns a pair: the current state value and a function that lets you update it.
You can call this function from an event handler or somewhere else. It’s similar
to this.setState in a class, except it doesn’t merge the old and new state together. (We’ll show
an example comparing useState to this.state in Using the State Hook.)
Declaring multiple state variables
You can use the State Hook more than once in a single component:
function ExampleWithManyStates() {
// ...
The array destructuring syntax lets us give different names to the state variables we
declared by calling useState. These names aren’t a part of the useState API. Instead, React
assumes that if you call useState many times, you do it in the same order during every
render.
Hooks are functions that let you “hook into” React state and lifecycle features from function
components. Hooks don’t work inside classes — they let you use React without classes.
React provides a few built-in Hooks like useState. You can also create your own Hooks to
reuse stateful behavior between different components.
The Effect Hook, useEffect, adds the ability to perform side effects from a function
component. It serves the same purpose as componentDidMount, componentDidUpdate,
and componentWillUnmount in React classes, but unified into a single API. (We’ll show
examples comparing useEffect to these methods in Using the Effect Hook.)
For example, this component sets the document title after React updates the DOM:
function Example() {
useEffect(() => {
return (
Click me
</button>
</div>
);
}
❑ When you call useEffect, you’re telling React to run your “effect” function after flushing
changes to the DOM. Effects are declared inside the component so they have access to
its props and state. By default, React runs the effects after every render —
including the first render. (We’ll talk more about how this compares to class lifecycles
in Using the Effect Hook.)
❑ Effects may also optionally specify how to “clean up” after them by returning a
function. For example, this component uses an effect to subscribe to a friend’s online
status, and cleans up by unsubscribing from it:
import React, { useState, useEffect } from 'react';
function FriendStatus(props)
function handleStatusChange(status)
setIsOnline(status.isOnline);
useEffect(() => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); };
);
return 'Loading...';
}
Rules of Hooks
❑ Hooks are JavaScript functions, but they impose two additional rules:
❑ Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested
functions.
❑ Only call Hooks from React function components. Don’t call Hooks from regular
JavaScript functions.
3.6.3 )React-Router HOOKS
React-Router is a popular React library that is heavily used for client-side routing and
offers single-page routing. It provides various Component APIs( like Route, Link, Switch,
etc.) that you can use in your React application to render different components based on
Hooks Of React Router 5: React Router 5 offers 4 hooks that you can use in your react
applications:
✓ useHistory
✓ useParams
✓ useLocation
✓ useRouteMatch
1. useHistory:
This is one of the most popular hooks provided by React Router. It lets you access the
history instance used by React Router. Using the history instance you can redirect users
to another page. The history instance created by React Router uses a Stack( called
“History Stack” ), that stores all the entries the user has visited.
Syntax :
Suppose, inside the “LogIn.js”, we have a “LogIn” component that renders the log-in page.
The LogIn component renders two input fields, one for the username and another for a
password. When the user clicks the login button, we want to authenticate the user and
redirect the user to his/her profile page.
import { useHistory } from "react-router-dom";
authenticateUser(userName, password);
history.push(`/profile/${userName}`);
};
return (
<div>
<input
type="text"
value={userName}
onChange={(e) => {
setUserName(e.target.value);
}}
required
/>
<input
type="text"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
required
/>
<button type="submit" onClick={handleClick}>
{" "}
Log In{" "}
</button>
</div>
);
}
2. useParams:
This hook returns an object that consists of all the parameters in URL.
import { useParams } from "react-router-dom"; // Inside a functional component export
These URL parameters are defined in the Route URL. For example,
For example, in the url “/profile/johndoe”, “johndoe” is the value of the parameter
{ userName: "johndoe" }
Example: After the login we want our user to be redirected to the “profile/userName”
URL. The userName depends on the user’s given name. So, we need to set the URL
path dynamically based on the user given userName. This is easy to do, we need to
App.js
return (
<div className="App">
<Switch>
</Route>
<Route path="/about">
<AboutUs />
</Route>
<Route path="/contact-us">
<ContactUs />
</Route>
<Route path="/log-in">
<LogIn />
</Route>
<Route path="/profile/:userName">
<Profile />
</Route>
</Switch>
</div>
);
}
Profile.js
return (
<div>
</div>
);
Output: Now if you now go to the log-in page and click the login button with userName
This hook returns the location object used by the react-router. This object represents the
current URL and is immutable. Whenever the URL changes, the useLocation() hook
returns a newly updated location object. Some of its use includes extracting the query
parameters from the URL and doing something depending on the query parameters. The
“search” property of the location object returns a string containing the query part of the
URL.
Syntax :
Note: history.location also represents the current location, but it is mutable, on the other
hand, the location returned by useLocation() is immutable. So, if you want to use the
Example: The useLocation() is very useful to get and use the query parameters defined
in the URL. In the below code we have used the useLocation hook to access the query
constructor(props)
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
handleSubmit(event)
render()
return
<form onSubmit={this.handleSubmit}>
</label>
</form> );
Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes
easier to integrate React and non-React code when using uncontrolled components. It
can also be slightly less code if you want to be quick and dirty. Otherwise, you should
internally. They use a ref to access the DOM element's current value and update the
state accordingly.
❑ A controlled functional component is a component that receives its current value and
update callback via props. For example, consider a simple form that accepts an email
address
const ControlledInput = (
);
return (
<form>
<ControlledInput
value={password}
onChange={setPassword}
placeholder="Password"
/>
<button>Submit</button>
</form>
);
};
❑ In this example, the ControlledInput component receives its current value and
an onChange callback via props. The LoginForm component maintains the state of
email and password, and when the user types into the inputs, it calls
the onChange callback and updates the state, which in turn updates the input values.
❑ An uncontrolled component in React is a component that does not store its form data
in its internal state. Instead, it lets the DOM handle the form data directly. Here is an
example:
import React, { useRef } from "react";
console.log("Email:", email);
console.log("Password:", password);
};
return (
<form onSubmit={handleSubmit}>
<UncontrolledInput ref={emailRef} placeholder="Email" />
<UncontrolledInput ref={passwordRef} placeholder="Password" />
<button type="submit">Submit</button>
</form>
);
};
❑ In this example, UncontrolledInput using the useRef hook to create references
(emailRef and passwordRef) to the input fields. When the form is submitted, we can
access the values of the input fields directly through these refs.
Prior to React v16, returning multiple elements from a component required to wrap them in
return <div>
<p>Hello, World!</p>
</div>;
};
<div>
<p>Hello, World!</p>
</div>
Starting with React v16, a single component can return multiple components without a
return props.children;
};
return <Aux>
<p>Hello, World!</p>
</Aux>;
};
<p>Hello, World!</p>
As you can see, react-aux is literally just 3 lines of code. Therefore, you could implement it
in your own codebase without using react-aux. However, props => props.children on its
own does not explain the intent. react-aux as an abstraction serves the purpose of enabling
a self-documenting code, i.e. the next time you see someone doing:
return <Aux>
<p>Hello, World!</p>
</Aux>;
};
3.9 ) HOW TO PASS DATA FROM CHILD COMPONENT TO ITS PARENT IN
REACTJS ?
data is passed from parent components to child components. However, there are
scenarios where you may need to pass data from a child component back to its
parent component.
❑ Data can be passed from the parent to the child component via props. Any
passed to the child component as props. While there is no direct way to pass data
from the child to the parent component, there are workarounds. The most
common one is to pass a handler function from the parent to the child component
that accepts an argument which is the data from the child component. This can
Approach:
Following are the steps to pass data from the child component to the parent
component:
➢ In the parent component, create a callback function. This callback function will
➢ Pass the callback function to the child as a props from the parent component.
➢ The child component calls the parent callback function using props and passes the
The initial state of the message variable in the Parent component is set to ‘Hello World’ and
it is displayed within the h1 tags in the Parent component as shown. We write
a chooseMessage function in the Parent component and pass this function as a prop to
the Child component. This function takes an argument message. But data for
this message argument is passed from within the Child component as shown. So, on click of
the Change Message button, msg = ‘Goodbye’ will now be passed to
the chooseMessage handler function in the Parent component and the new value
of message in the Parent component will now be ‘Goodbye’.
This way, data from the child component(data in the variable msg in
Child component) is passed to the parent component.
10. ASSIGNMENT – 1 To 5
Assignment I : (CO3,CO4,K2)
1. What is the difference between Class Components and Functional Components in
React? Provide examples.
2. Explain the role of props in React. Are they mutable or immutable? How do they
flow between components?
3. Write a simple React functional component that uses useState to toggle a boolean
value.
4. What are controlled and uncontrolled components in React? Explain with examples.
5. What is PropTypes in React? How does it help in maintaining type safety? Provide an
example.
Assignment V: (CO3,CO4,CO5,K5)
1. Develop a full-fledged React application that includes a Login Page, Dashboard, and
Admin Page with authentication using protected routes.
2. Implement a customer management system using WeakMap and Map collections in
JavaScript.
3. Demonstrate the differences and benefits of each.Create a React application that
integrates with an external API, fetches data, and displays it using a paginated list.
4. Build a component that allows users to enter form data using controlled
components, validates inputs, and displays error messages dynamically.
5. Implement a complex parent-child interaction system where a parent component
provides state updates to multiple child components and receives updates from
them..
11. PART-A : QUESTIONS AND ANSWERS
A Component is one of the core building blocks of React. In other words, we can say that
every application you will develop in React will be made up of pieces called components.
Components make the task of building UIs much easier. You can see a UI broken down
into multiple individual pieces called components and work on them independently and
merge them all in a parent component which will be the final UI.
Components in React basically return a piece of JSX code that tells what should be
rendered on the screen.
Types of components in ReactJS
In React, we mainly have two types of components:
1. Class Based Component
2. Function Based Component
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
11. PART-A : QUESTIONS AND ANSWERS
❑ The state is an updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state over
time can happen as a response to user action or system event. A component with the
state is known as stateful components. 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.
❑ A state must be kept as simple as possible. It can be set by using the setState() method
and calling setState() method triggers UI updates. A state represents the component's
local state or information. It can only be accessed or modified inside the component or
by the component directly. To set an initial state before any interaction occurs, we need
to use the getInitialState() method.
❑ For example, if we have five components that need data or information from the state,
then we need to create one container component that will keep the
state for all of them.
10 . Mention State in React (CO4,K2)
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.
Example
The below sample code shows how we can create a stateful component using ES6 syntax.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: true };
}
render() {
const bio = this.state.displayBio ? (
<div>
<p><h3> 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.</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to REACT CLASS</h1>
{ bio }
</div>
);
}
}
export default App;
11. How do you change the state in react? ( CO3,K2)
We can change the component state by using the setState() method and passing a new state
object as the argument. Now, create a new method toggleDisplayBio() in the above example
and bind this keyword to the toggleDisplayBio() method otherwise we can't access this inside
toggleDisplayBio() method.
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
The componentDidMount() method enables us to execute the React code when the
component is already placed in the Document Object Model. All the AJAX requests and the
DOM or state updation should be coded in the componentDidMount() method block. After all
the elements of the page are rendered correctly, this method is called. After the markup is set
on the page, this technique is called by React itself to either fetch the data from an External
API or perform some unique operations which need the JSX elements.
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. The updating phase includes several lifecycle hooks; requests.
15. Define the below: (CO4,K2)
getDerivedStateFromProps
This method is invoked right before calling the render method, both on the initial mount and
on subsequent updates. It should return an object to update the state, or null to update
nothing. The method exists for rare use cases where the state depends on changes in props
over time.
shouldComponentUpdate ()
The shouldComponentUpdate () method may be used to let React know if a component’s
output is not affected by the current change in state or props. The default behaviour is to re-
render on every state change, and in the vast majority of cases, you should rely on the
default behaviour.
componentDidUpdate ()
The componentDidUpdate method is called after the component is updated in the DOM. The
componentDidUpdate lifecycle method is invoked after the getSnapshotBeforeUpdate. As with
the getSnapshotBeforeUpdate method, it receives the previous props and state as arguments.
Whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as
the third argument to the componentDidUpdate method. nnecessary network
The Effect Hook, useEffect, adds the ability to perform side effects from a function
component. It serves the same purpose as componentDidMount, componentDidUpdate,
and componentWillUnmount in React classes, but unified into a single API. (We’ll show
examples comparing useEffect to these methods in Using the Effect Hook.)
For example, this component sets the document title after React updates the DOM:
❑ Hooks are JavaScript functions, but they impose two additional rules:
❑ Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested
functions.
❑ Only call Hooks from React function components. Don’t call Hooks from regular
JavaScript functions.
24. List out the Difference between Controlled and Uncontrolled Components
(CO3,K2)
This is one of the most popular hooks provided by React Router. It lets you access the history
instance used by React Router. Using the history instance you can redirect users to another
page. The history instance created by React Router uses a Stack( called “History Stack” ), that
stores all the entries the user has visited.
Syntax :
This hook returns an object that consists of all the parameters in URL.
These URL parameters are defined in the Route URL. For example,
For example, in the url “/profile/johndoe”, “johndoe” is the value of the parameter
{ userName: "johndoe" }
https://www.coursera.org/learn/react-basics
https://www.udemy.com/course/react-the-complete-
guide-incl-redux/learn/
https://cs50.harvard.edu/web/2020/
75
14. REAL TIME APPLICATIONS
At Spaculus, we can incorporate your new website design or we modify it and make it
responsive if you already own a website. Our team of experts uses various tools and
technologies to make your website more accessible such as media queries, flexible
grid based layouts that use re-sizing and flexible images & media.
jsx
import React from 'react';
79
16. ASSESSMENT SCHEDULE
Name of the
S.NO Start Date End Date Portion
Assessment
As per schedule after
1 Unit Test 1 UNIT 1
Unit I completion
2 IAT 1 28.01.2025 03.02.2025 UNIT 1 & 2
163
80
17. PRESCRIBED TEXT BOOKS
&
REFERENCE BOOKS
TEXT BOOKS:
Full-Stack React, TypeScript, and Node: Build cloud-ready web applications using React 17
with Hooks and GraphQL Paperback – Import, 18 December 2020
REFERENCES:
The Road to Learn React: Your journey to master plain yet pragmatic React.js by Robin
Wieruch
Learning React: Functional Web Development with React and Redux by Alex Banks and Eve
Porcello
https://www.edureka.co/reactjs-redux-certification-training
CodePen,
CodeSandbox (ß Preferred)
Stackblitz.
18. MINI PROJECT SUGGESTION
By manipulating the DOM, you have infinite possibilities. You can create applications that
update the data of the page without needing a refresh. Also, you can create applications
that are customizable by the user and then change the layout of the page without a
refresh.
2) JAVASCRIPT CLOCK (CO3,K3)
Key concepts covered:
Variables
Conditional logic
Program flow
Functions
3)To-Do List (CO3,K3)
Why do this project?
You’ll beef up your skills at coding interactive lists, which lets users add, remove, and group
items
You can use this beginner JavaScript project in your daily life and add it to your portfolio
Learn more about how to use arrays, nested functions, and local storage API
4) Tic_Tac-Toe (CO4,K3)
Implement the JavaScript code so that the player can set difficulty level as easy or hard,
choose whether to play as X or O, play a game with the computer, have it remember who
won or drew, and play again.
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
relianceon the contents of this information is strictly prohibited.