0% found this document useful (0 votes)
6 views

Unit 17 ReactJS Student's Guide

This document serves as a student guide for Unit 17 on ReactJS, outlining the goals and outcomes for learning React, including its basic concepts, advantages, and practical applications. It covers topics such as the Virtual DOM, component-based architecture, JSX, and the differences between ReactJS and React Native. The guide also includes instructions for setting up a React development environment and creating a basic application.

Uploaded by

youssefhn632
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 17 ReactJS Student's Guide

This document serves as a student guide for Unit 17 on ReactJS, outlining the goals and outcomes for learning React, including its basic concepts, advantages, and practical applications. It covers topics such as the Virtual DOM, component-based architecture, JSX, and the differences between ReactJS and React Native. The guide also includes instructions for setting up a React development environment and creating a basic application.

Uploaded by

youssefhn632
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

IT Department

Web Development and Programming

‫تطوير المواقع والبرمجيات‬


‫الصف الثالث‬
Unit 17 ReactJS

Web Development and Programming


STUDENT GUIDE

1st.
2024 - 2025
‫تطوير المواقع والبرمجيات‬
Unit 17 ReactJS
‫الصف الثالث‬

Web Development and Programming


STUDENT GUIDE

2
Unit 17
ReactJS
Unit 17
Name ReactJS
Goals / By the end of this Unit, students should be able to:
Outcomes ➢ Remembering
1. Recall the basic concepts, history, and uses of React.js,
including the Virtual DOM, React components, state,
props, hooks, and routing.
2. Identify the advantages and differences of React
components, Hooks, and React Router.
➢ Understanding
1. Explain the principles of React, including how it integrates
with the Virtual DOM and the importance of state and
props in building dynamic UIs.
2. Describe the use and differences between functional and
class components, state management techniques, and the
purpose of different Hooks (useState, useReducer,
useContext, useEffect).
3. Understand client-side vs. server-side rendering and how
React Router manages routing in single-page applications.
➢ Applying
1. Set up a React development environment and create basic
React applications using create-react-app.
2. Implement and manage state in functional and class
components using useState, useReducer, and useContext.
3. Create and render React components, establishing parent-
child relationships and passing data through props.
4. Use React Router to create a multi-route single-page
application with navigation and dynamic routes.

3
5. Apply various styling methods (CSS Modules, inline
styles, JavaScript objects) and integrate third-party
libraries like Bootstrap.
6. Utilize useEffect for managing side effects and component
lifecycle events.
➢ Analyzing
1. Analyze the role of the Virtual DOM in performance, and
compare functional and class components.
2. Evaluate the differences and appropriate use cases for
useState vs. useReducer.
3. Compare the advantages and implications of using SSR vs.
CSR in React applications.
4. Examine the impact of different routing and state
management techniques on application behavior and
structure.
➢ Evaluating
1. Assess the suitability and impact of using React.js, Hooks,
and React Router for different types of projects.
2. Evaluate the benefits of various state management
approaches and the use of useContext for sharing state
across components.
3. Judge the effectiveness of React Router in managing
single-page applications and the pros and cons of SSR and
CSR.
➢ Creating
1. Build a dynamic React application that utilizes
components, state, props, and Hooks for interactivity and
state management.
2. Design complex component hierarchies with effective state
sharing using useContext.
3. Develop a single-page application with multiple routes,
dynamic navigation, and SSR using React Router.
4. Implement a state-sharing mechanism and lifecycle
management using various Hooks (useState, useReducer,
useContext, useEffect).

4
Code Description
TPK20 writing asynchronous code using various
techniques
Knowledge TPK21 Basic routing and calling a controller method
from a route
TPK22 Analyze and solve common web applications
tasks by writing PHP programs
Code Description
TPC5.4 Using UI Framework (React)
Skill TPC5.5 Creating an authentication system for your
application
TPC5.7 Using controllers and routes for APIs and URLs

5
Unit Preface

6
Lesson 1
Name Introduction to React
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Recall the basic concepts of React.js and its history.
2. Identify the uses and applications of React.js.
3. List the advantages of the Virtual DOM and the
components of a React development environment.
➢ Understanding
1. Explain what React.js is and why it is widely used in
web development.
2. Describe how React.js integrates with the Virtual DOM.
3. Understand the differences between React.js and React
Native, including their specific use cases.
➢ Applying
1. Install Node.js and set up a new React app using the
create-react-app tool.
2. Write and execute a basic "Hello World" application
using React.js.
3. Use JSX to create simple React components and render
them in the browser.
➢ Analyzing
1. Analyze the role of the Virtual DOM in React.js and
how it improves performance.
2. Compare React.js with other JavaScript libraries or
frameworks in terms of component-based architecture
and performance.
➢ Evaluating
1. Assess the performance advantages of using React.js
with the Virtual DOM in web applications.
2. Evaluate the suitability of React.js and React Native for
different types of projects, including web and mobile
applications.
➢ Creating

7
1. Develop and design basic React components using JSX
to build dynamic web content.
2. Create a simple React application that utilizes
component-based architecture and demonstrates the use
of the Virtual DOM.

writing asynchronous code using various


TPK20
techniques
Knowledge
Analyze and solve common web applications
TPK22
tasks by writing PHP programs
Code Description
Skill TPC5.4 Using UI Framework (React)
TPC5.7 Using controllers and routes for APIs and URLs

8
Lesson One: Introduction To React

IN THIS LESSON WE LEARN:


1. Introduction ReactJS
1. What is React.js?
2. Why Choose React.js?
2. The Virtual DOM
1. Virtual DOM concept
2. How its Virtual DOM Works
3. Advantages of the Virtual DOM
3. Getting Started with React.js
1. Installing Node
2. Creating a New React App
4. Creating Your First "Hello World" Application
5. JSX In ReactJS
1. What is JSX?
2. Features of JSX
6. Difference between ReactJS and React Native
1. ReactJS
2. React Native

9
Section 1: Introduction ReactJS

1-1 Introduction ReactJS


ReactJs is one of the most widely used front-end JavaScript libraries for
creating Web Applications. Around 8,000 businesses around the world
have chosen React over other popular libraries and frameworks for building
rich user interfaces. React is a Facebook-developed JavaScript package that
was used to create Instagram, among other things. It is like a panacea for
developers to build user interfaces for websites and apps swiftly. The
virtual DOM is the core notion of ReactJs.

1-2 What is React.js?


React.js, commonly referred to as React, is an open-source JavaScript
library maintained by Facebook and a vibrant community of developers. It
is primarily used for creating user interfaces (UI) for single-page
applications (SPAs) and is based on the concept of reusable components.

1-3 Why Choose React.js?


React JS is a popular JavaScript library for building user interfaces and
creating dynamic and engaging web experiences. It is used by some of the
biggest companies in the world, including Facebook, Instagram, and
Netflix. What are its key features?

10
Component-Based Architecture: ReactJS developers can build
reusable UI components that can easily be combined to create complex
web applications. This modular approach to UI design makes it easier to
maintain code and speed up development time.
2. Virtual DOM: ReactJS uses a virtual DOM (Document Object
Model) that updates only the parts of the DOM that need to be updated
whenever a change occurs. This approach results in faster rendering
times and better application performance,
3. Declarative Syntax: ReactJS uses a declarative syntax, which makes
it easier for developers to understand and maintain code. This syntax
enables developers to write code that describes exactly how the UI
should look rather than writing code that manipulates the UI directly.
4. Server-Side Rendering: ReactJS can be used for server-side
rendering, which improves the initial load time of a web application and
makes it easier for search engines to index the application.
5. Large Ecosystem: ReactJS has a large ecosystem of third-party tools
and extensions, making it a great choice for all projects regardless of its
size.

11
The world’s most widely used web frameworks among developers
(source Statista 2024)
Section 2 The Virtual DOM
2-1 Virtual DOM concept
The Virtual DOM is a programming concept used in modern JavaScript
frameworks like React and Vue.js. It's a lightweight, in-memory
representation of the actual DOM (Document Object Model) of a web page.

2-2 How it works:


1. Initial Rendering: When a component is first rendered, the
framework creates a virtual DOM representation of the component's
UI.

12
2. Updates: When the component's state or props change, the
framework updates the virtual DOM.
3. Diffing: The framework compares the old and new virtual DOMs to
identify the minimal set of changes needed to update the actual
DOM.
4. Patching: The framework applies the necessary changes to the actual
DOM, updating only the affected parts.

2-3 Advantages of the Virtual DOM:


• Performance: By minimizing direct manipulations to the actual
DOM, the Virtual DOM can significantly improve rendering
performance, especially for complex UI updates.
• Declarative Programming: Developers can focus on describing the
desired UI state, and the framework handles the updates efficiently.
• Cross-Platform Compatibility: The Virtual DOM can be used to
render UI for different platforms, such as web, mobile, and desktop
applications.

13
Section 3 Getting Started with React.js:
3-1 Installing Node.
Now, let’s take the first step into the world of React.js and set up our
development environment.

• Installing Node.js and npm: Before we begin, make sure you have
Node.js and npm (Node Package Manager) installed on your system.
You can download and install the latest version from the official
Node.js website : Download Node.js
• Creating a New React App: Once Node.js and npm are installed, open
your terminal or command prompt. Use the following command to
create a new React app
3-2 Creating a New React App
npx create-react-app my-react-app
This will set up a new React.js project with the name "my-react-app" in
your current directory.
Starting the Development Server: Change your working directory to the
newly created project folder using the "cd" command:
cd my-react-app

14
To see your "Hello World" application in action, start the development
server with the following command:
npm start
Your React.js application will now be accessible at "http://localhost:3000"
in your web browser.

Section 4 Creating Your First "Hello World" Application:


Now that we have our project set up, let’s write our first “Hello World”
application using React.js.
1. Edit App.js: In the "src" folder of your project, open the "App.js" file
in your code editor.
2. Write "Hello World" Code: Inside the "App.js" file, replace the
default content with the following code:
import React from 'react';
function App() {
return (
<div>
<h1>Hello World</h1>
</div>
);
}
export default App;
This code creates a functional component called “App” that renders a
simple heading displaying “Hello World.”

15
Section 5 JSX In ReactJS?
5-1 What is JSX?
JSX is a syntax extension for JavaScript that allows you to write HTML-
like code within JavaScript files. It is not a template language but rather a
preprocessor that gets transformed into regular JavaScript code before it's
executed.

5-2 Features of JSX:


• HTML-like Syntax: JSX uses syntax like HTML, making it easier to
write and understand UI components.
• Embedding Expressions: You can embed JavaScript expressions
directly within JSX tags using curly braces ({}). This allows you to
dynamically render content based on data.
• JSX Fragments: To render multiple elements without a parent
container, you can use JSX fragments enclosed in angle brackets with
key attributes.
• Conditional Rendering: You can conditionally render different
elements based on conditions using JavaScript expressions within
JSX.
• List Rendering: JSX provides a concise way to render lists of
elements using the map() method.

16
Section 6 Difference between ReactJS and React Native

6-1 ReactJS
ReactJS is an open-source JavaScript library used to build the user interface
for Web Applications. It is responsible only for the view layer of the
application. It provides developers to compose complex UIs from a small
and isolated piece of code called "components." ReactJS made of two parts
first is components, that are the pieces that contain HTML code and what
you want to see in the user interface, and the second one is HTML
document where all your components will be rendered.
Advantage of ReactJS
1. Easy to Learn and Use: ReactJS is much easier to learn and use.
Any developer who comes from a JavaScript background can easily
understand and start creating web apps using React.
2. Creating Dynamic Web Applications Becomes Easier: To create a
dynamic web application specifically with HTML was tricky, which
requires complex coding, but React JS solved that issue and makes it
easier. It provides less coding and gives more functionality.
3. Reusable Components: A ReactJS web application is made up of
multiple components, and each component has its logic and controls.
These components can be reused wherever you need them. The
reusable code helps to make your apps easier to develop and maintain.

17
4. Performance Enhancement: ReactJS improves performance due to
virtual DOM. The React Virtual DOM exists entirely in memory and
is a representation of the web browser's DOM. Due to this, when we
write a React component, we did not write directly to the DOM.
Instead, we are writing virtual components that react will turn into the
DOM, leading to smoother and faster performance.
5. The Support of Handy Tools: ReactJS supports a handy set of tools
which make the task of the developers understandable and easier. It
also allows you to select components and examine and edit their
current Props and State.

6-2 React Native


React Native is an open-source JavaScript framework used for developing a
mobile application for iOS Android, and Windows. It uses only JavaScript
to build a cross-platform mobile app. React Native is the same as React, but
it uses native components instead of using web components as building
blocks. It targets mobile platforms rather than the browser.
Facebook develops the React Native in 2013 for its internal project
Hackathon. In March 2015, Facebook announced that React Native is open
and available on GitHub.
Advantages of React Native
There are several advantages of React Native for building mobile
applications. Some of them are given below:
1. Cross-Platform Usage: It provides the facility of "Learn once write
everywhere." It works for both platform Android as well as iOS
devices.
2. Class Performance: The code written in React Native is compiled
into native code, which enables it for both operating systems as well
as it functions in the same way on both the platforms.
3. JavaScript: JavaScript knowledge is used to build native mobile
apps.
4. Community: The large community of ReactJS and React Native
helps us to find any answer we require.
18
5. Hot Reloading: Making a few changes in the code of your app will
be immediately visible during development. If the business logic is
changed, its reflection is live reloaded on screen.
6. Improving with Time: Some features of iOS and Android are still
not supported, and the community is always inventing the best
practices.
7. Native Components: We will need to write some platform specific
code if we want to create native functionality, which is not designed
yet.

SN ReactJS React Native


1. The ReactJS initial release The React Native initial release was in
was in 2013. 2015.
2. It is used for developing It is used for developing mobile
web applications. applications.
3. It can be executed on all It is not platform independent. It takes
platforms. more effort to be executed on all
platforms.
4. It uses a JavaScript library It comes with built-in animation
and CSS for animations. libraries.
5. It uses React-router for It has built-in Navigator library for
navigating web pages. navigating mobile applications.
6. It uses HTML tags. It does not use HTML tags.
7. It can use code components, It can reuse React Native UI
which saves a lot of components & modules which allow
valuable time. hybrid apps to render natively.
8. It provides high security. It provides low security in comparison
to ReactJS.
9. In this, the Virtual DOM In this, Native uses its API to render
renders the browser code. code for mobile applications.

19
Terminology:
• React.js (ReactJS): A JavaScript library by Facebook for building
UIs in single-page apps using reusable components.
• Virtual DOM: An in-memory version of the DOM used by ReactJS
to optimize rendering by updating only changed elements.
• JSX (JavaScript XML): A syntax for writing HTML-like code in
JavaScript files, transformed into standard JavaScript before running.
• React Native: A framework for building mobile apps for iOS,
Android, and Windows using native components.

20
Dear learner: Put "True" in front of the correct statement and "False" in front
of the incorrect statement.

No Question Answer

1 React.js is primarily used for creating back-end


applications.
2 React uses the Virtual DOM to improve performance by
minimizing updates to the actual DOM.
3 JSX is a templating language used in React.
4 React Native allows for building cross-platform mobile
apps using the same codebase.
5 ReactJS uses the browser's DOM directly for rendering.
6 ReactJS and React Native both support the concept of
reusable components.
7 The "npm start" command launches the production build
of a React app.
8 ReactJS provides a declarative syntax for writing UI
components.

Dear learner: Choose the correct answer.


No. Question Answer
9 What does React.js primarily focus on?
a) Back-end development
b) Game development

21
c) User interfaces for web applications
d) Database management
10 Which concept is the core of ReactJS?
a) Middleware
b) Virtual DOM
c) MVC architecture
d) JavaScript templates
11 What is JSX?
a) A new programming language
b) A syntax extension for JavaScript
c) A database query language
d) A version of HTML
12 ReactJS can be used for which of the following?
a) Only mobile applications
b) Only web applications
c) Both web and mobile applications
d) Only desktop applications
13 Which command is used to create a new React.js
application?
a) npm create-react-app
b) create-react-project
c) npx create-react-app
d) react-init
14 What feature of React helps optimize the performance of
UI updates?
a) Real-time Database
b) Virtual DOM
c) Stateful Components
d) REST API

22
15 React Native is used to build:
a) Web applications
b) Desktop applications
c) Mobile applications
d) None of the above
16 Which of the following is true about React.js?
a) It uses two-way data binding
b) It is based on reusable components
c) It is designed for back-end development
d) It doesn't use JavaScript

Dear learner: Complete the question.


No. Question Answer
17 React.js is primarily used for creating user interfaces
for ______ applications.
18 The main concept behind React’s performance
optimization is the ______ DOM.

19 JSX is transformed into regular ______ before


execution.
20 In JSX, JavaScript expressions are embedded using
______.

23
Lesson 2
Name Rendering UI with React
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Recall the basic concepts and types of React
components.
2. Identify the advantages of using React components.
3. List the methods for styling React components,
including CSS Modules, inline styles, and global styles.
➢ Understanding
1. Explain what React components are and their
importance in building UIs.
2. Describe the differences between functional and class
components in React.
3. Understand the parent-child relationship in React
components and how data is passed through props.
➢ Applying
1. Create and render functional and class components in a
React application.
2. Use parent-child relationships to build nested React
components.
3. Apply different styling methods (CSS Modules, inline
styles, JavaScript objects, and global styles) to React
components.
➢ Analyzing
1. Analyze the differences between functional and class
components, and determine when to use each.
2. Compare the various methods of styling React
components and their impact on component isolation
and reusability.
➢ Evaluating
1. Assess the advantages of using React components for
creating reusable and maintainable UI elements.

24
2. Evaluate the use of Bootstrap with React and its
methods of integration (using a CDN and package
manager).
➢ Creating
1. Develop React components using both functional and
class-based approaches.
2. Design a React application that uses parent-child
relationships to pass data and render complex UIs.
3. Implement styling for React components using CSS
Modules, inline styles, JavaScript objects, and global
styles.
4. Integrate Bootstrap into a React application using a
CDN or package manager.
writing asynchronous code using various
TPK20
techniques
Knowledge
Analyze and solve common web applications
TPK22
tasks by writing PHP programs
Code Description
Skill TPC5.4 Using UI Framework (React)
TPC5.7 Using controllers and routes for APIs and URLs

25
Lesson Two: Rendering UI with React

IN THIS LESSON WE LEARN:


1. React COMPONENT
1. Understanding Components
2. Advantages of using React Components
2. Types of Components in React
1. Functional Component in React
2. Class Component in React
3. Functional Component vs Class Component
3. Rendering React and parent-child Components
1. Rendering React Components
2. Parent-Child Relationships
4. Styling React components using CSS
1. CSS Modules
2. Inline Styles
3. JavaScript Object
4. Global Styles
5. Using Bootstrap with React
1. Using a CDN
2. Using a Package Manager

26
Section 1: React COMPONENT
1-1 Understanding Components
React components are the building blocks of a React application. They are
like custom HTML elements that you can reuse throughout your app.
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.

Here we 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.

1-2 Advantages of using React Components:


Components promote reusability and maintainability. They allow you to
break down your UI into smaller, manageable pieces.

27
Section 2 Types of Components in React
In React, we mainly have two types of components:
• Functional Components
• Class based Components
2-1 Functional Component in React
Functional components are just like JavaScript functions that accept
properties and return a React element.
We can create a functional component in React by writing a JavaScript
function. These functions may or may not receive data as parameters, we
will discuss this later in the tutorial. The below example shows a valid
functional component in React:
Syntax:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}

2-2 Class Component in React


The class components are a little more complex than the functional
components. A class component can show inheritance and access data of
other components.
Class Component must include the line “extends React.Component” to
pass data from one class component to another class component. We can
use JavaScript ES6 classes to create class-based components in React.
Syntax:
class Democomponent extends React.Component {
render() {
return <h1>Welcome Message!</h1>;
}
}
28
2-3 Functional Component vs Class Component
A functional component is best suited for cases where the component
doesn’t need to interact with other components or manage complex states.
Functional components are ideal for presenting static UI elements or
composing multiple simple components together under a single parent
component.
While class-based components can achieve the same result, they are
generally less efficient compared to functional components. Therefore, it’s
recommended to not use class components for general use.

Section 3 Rendering React and parent-child Components


3-1 Rendering React Components
Rendering Components means turning your component code into the UI
that users see on the screen.

React is capable of rendering user-defined components. To render a


component in React we can initialize an element with a user-defined
component and pass this element as the first parameter to
ReactDOM.render() or directly pass the component as the first argument to
the ReactDOM.render() method.
The ReactDOM.render() method is the linchpin between React and the
browser's DOM. It takes a React element, transforms it into a DOM
element, and injects it into the actual HTML DOM.
29
3-2 Parent-Child Relationships:
In React, components can be nested within other components, forming a
hierarchical structure. This creates a parent-child relationship between
components.

Passing Props:
• Parent components can pass data to their child components as props.
• Props are immutable values that are passed down from parent to child
components.
• Child components can access and use these props to render their own
UI.
Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

30
function WelcomeMessage(props) {
return (
<div>
<Greeting name={props.name} />
<p>Welcome to our website!</p>
</div>
);
}
In this example, the WelcomeMessage component is the parent component,
and the Greeting component is the child component. The WelcomeMessage
component passes the name prop to the Greeting component, which is then
used to render the greeting message.

31
Section 4 Styling React components using CSS

4-1 CSS Modules:


Isolation CSS Modules provide a way to scope CSS styles to specific
components, preventing naming conflicts and ensuring style isolation.
To use CSS Modules, import the CSS file and use the generated class
names in your JSX.
Example:
import styles from './MyComponent.module.css';
function MyComponent() {
return (
<div className={styles.container}>
<h1 className={styles.title}>My Component</h1>
</div>
);
}

4-2 Inline Styles:


Directly in JSX: Inline styles can be applied directly to elements within
JSX using the style attribute.
Object Syntax: Styles are defined as JavaScript objects with camelCase
property names.
Example:

32
function MyComponent() {
return (
<div style={{ color: 'red', fontSize: '24px' }}>
My Component
</div>
);
}
4-3 JavaScript Object
You can also create an object with styling information, and refer to it
in the style attribute:
function MyComponent() {
const style = { color: "red", backgroundColor: "yellow" };
return (
<div >
<h1 style={style}> Welcome From Component </h1>
</div>
);
}

4-4 Global Styles:


CSS Files: Create separate CSS files for global styles that apply to multiple
components.
Import: Import these CSS files into your main JavaScript file or use a CSS
loader.
Example:
import './global.css';
// ... your component code

33
Section 5 Using Bootstrap with React
how to use React and Bootstrap, and how to add bootstrap to React app.

5-1 Using a CDN:


Include Bootstrap's CSS and JavaScript files directly in your index.html
file:
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.
min.css">
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bu
ndle.min.js"></script>

5-2 Using a Package Manager:


you can install Bootstrap using a package manager like npm or yarn:
In Terminal:
npm install bootstrap
Then, import Bootstrap's CSS in your index.js file:
import 'bootstrap/dist/css/bootstrap.min.css';
import "bootstrap/dist/js/bootstrap.bundle"

34
Terminology:
• React Components: Reusable building blocks of a React app, acting
like custom HTML elements.
• Functional Components: Simple JavaScript functions that return
React elements. Ideal for static UI elements.
• Class Components: More complex components using ES6 classes.
They manage their own state and show inheritance.
• Props: Immutable data passed from parent to child components, used
to render dynamic content.

35
Dear learner: Complete the question.
No. Question Answer
21 The Virtual DOM compares the old and new DOMs
to identify ______.
22 ReactJS is based on a ______ architecture, where
components can be reused.
23 A syntax extension in ReactJS that allows embedding
HTML-like code in JavaScript files is called ______.
24 ______ is used for developing Mobile applications.

Dear Learner: Answer the following questions.


Questio What is React.js, and how is it different from other
25 n JavaScript frameworks?
Answer

Question What is JSX ?


26
Answer

Question How does React Native differ from ReactJS?


27
Answer

Question What role do components play in React.js?


28
Answer

36
Dear learner: Put "True" in front of the correct statement and
"False" in front of the incorrect statement.
No Question Answer
29 React components can be nested within other
components.
30 Props are mutable and can be changed within a child
component.
31 A class component must extend React.Component.
32 Functional components can access and modify the state
without using hooks.
33 CSS Modules are used to avoid global CSS conflicts by
scoping styles to components.
34 You cannot use inline styles directly in JSX elements.
35 State is unique to each component and cannot be
accessed by other components directly.
36 Prop drilling refers to passing props from parent to
child through multiple layers.
37 React.memo is used to prevent unnecessary re-renders
of functional components.
38 You can only use state in functional components, not in
class components.

Dear learner: Choose the correct answer.

No. Question Answer


39 What is a key benefit of React components?
a) Improved performance

37
b) Global state management
c) Reusability and maintainability
d) None of the above

40 How do you create a functional component in React?


a) By writing a JavaScript class
b) By writing a JavaScript function
c) By using the render method
d) By using React.createComponent

38
Lesson 3
Name State Management
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Define state and props in React.
2. Identify the need for state management in React.
➢ Understanding
1. Explain how state is used in functional and class
components.
2. Describe the difference between state and props.
➢ Applying
1. Use useState in functional components.
2. Implement state in class components using this.state and
setState.
3. Pass and use props in child components.
➢ Analyzing
1. Compare state usage in functional vs. class components.
2. Analyze how to lift state up to manage shared data.
➢ Evaluating
1. Assess the importance of state management in larger
React apps.
2. Evaluate techniques for managing state and props in
component hierarchies.
➢ Creating
1. Create React components using state and props for
dynamic UIs.
2. Design component hierarchies with effective state and
props management.

Knowledge Code Description

39
TPK20 writing asynchronous code using various
techniques
TPK21 Basic routing and calling a controller method
from a route
Code Description
Skill
TPC5.4 Using UI Framework (React)
TPC5.7 Using controllers and routes for APIs and URLs

40
Lesson Three: State Management

IN THIS LESSON WE LEARN:


1. What Is State and Props
1. State in React
2. What is React State Management?
3. Why do you need React state management?
4. Using State in Functional Components
5. State in Class Components
2. Props in React
1. What are Props?
2. Managing State and Props in Component Hierarchy
3. Updating State and Triggering Re-renders
4. Lift State Up
5. Avoid Prop Drilling

41
Section 1 What Is State and Props
React is a popular JavaScript library for building user interfaces. Managing
state and props, which allow components to store and pass data. we will
explore what state and props are, their differences, and how to use them
effectively in React.

1-1 State in React:


In React, state is an object that holds data specific to a component. It
represents the current state of the component and can be changed over time.
State is managed internally by the component, it is used to render dynamic
content based on its values, user interactions, and managing component-
specific data. To define and update the state, we use the useState hook or
create a class-based component.
1-2 What is React State Management?
React components have a built-in state object. The state is encapsulated
data where you store assets that are persistent between component
renderings.
The state is just a fancy term for a JavaScript data structure. If a user
changes state by interacting with your application, the UI may look
completely different afterwards, because it's represented by this new state
rather than the old state.
1-3 Why do you need React state management?

42
React applications are built using components and they manage their state
internally and it works well for applications with few components, but
when the application grows bigger, the complexity of managing states
shared across components becomes difficult.
Here is a simple example of an e-commerce application, in which the status
of multiple components will change when purchasing a product.
• Add that product to the shopping list
• Add product to customer history
• trigger count of purchased products
If developers do not have scalability in mind, then it is hard to find out what
is happening when something goes wrong. This is why you need state
management in your application.

1-4 Using State in Functional Components:


Functional components are a popular way to build components in React.
With the introduction of React hooks, we can now use state in functional
components. The useState hook allows us to declare and update state
variables. The above given example make use of state in function
component.
Here’s an example of using state in a functional component:

43
In this example, we define a state variable called count and its
corresponding update function, setCount, using the useState hook. The
initial value of count is 0. In addition, we can then use the count variable
within the component’s JSX to render the current count value.
To update the state, we call the update function (setCount) and provide the
new value. In the increment function, we update the count by incrementing
it by 1. React will re-render the component with the updated state,
reflecting the changes in the UI.
It’s important to note that updating state is an asynchronous operation in
React.
Meanwhile, When the update function is called, React queues the state
update and performs a batch update to minimize re-renders. This helps
optimize performance.
State is local to a component, meaning it is not accessible or modifiable
from other components. If you need to share state between components,
you can lift the state up to a common ancestor component or use state
management libraries like Redux or Context API.

44
State management in class components follows a similar concept but uses
the this.state object and the setState method to update the state. Moreover
Class components provide lifecycle methods like componentDidMount and
componentDidUpdate that allow you to handle state initialization and
updates.
State is a crucial aspect of React that enables components to have
dynamic behavior and respond to user interactions. By managing state
effectively, you can create responsive and interactive user interfaces in
your React applications.

1-5 State in Class Components:


Prior to hooks, class components were commonly used in React. In class
components, state is defined using the this.state object. With the
introduction of Hook in React, class components are infrequently used.
Given is an example of class component.

Section 2 Props in React:

45
2-1 What are Props?
Props (short for properties) are a way to pass data from a parent component
to its child components. Unlike state, props are immutable and cannot be
changed within the child component. They are passed down as attributes to
child components and are accessible as read-only values. We’ll explore
how to pass props and access them within functional and class components.
Basically, Props allow components to be reusable, as they can receive
different data and render accordingly based on the provided props.
The child component receives the props as an argument and can access
their values. Here’s an example:

In this example, the parent component, ParentComponent, renders the child


component, ChildComponent, and passes two props: name and age. The
child component receives these props as an argument (commonly named
props), and we can access the values using dot notation (props.name,
props.age) within the child component’s JSX.

46
Props are read-only, meaning that they cannot be modified or reassigned
within the child component.
Props are meant to be used as immutable data that influences the rendering
and behavior of the child component. If the parent component updates the
props, the child component will be re-rendered with the updated values.
Props can be of any data type, including strings, numbers, Booleans,
objects, or even functions. In addition, they can also include other React
components, allowing for nested and composition-based component
structures.
Props in React allow for the passing of data from parent to child
components, enabling component reusability and flexibility. By utilizing
props effectively, you can create modular and customizable components
that compose together to build complex user interfaces.
2-2 Managing State and Props in Component Hierarchy:
In larger applications, components are organized into a hierarchy, where
parent components pass data to child components via props. We’ll discuss
how to handle state and props in component hierarchies, including best
practices for managing and updating data flow between components.

47
2-3 Updating State and Triggering Re-renders:
Additionally, react components re-render when there are changes in their
state or props. We’ll learn about the React reconciliation process, how state
updates trigger re-renders, and how to optimize performance by using
shouldComponentUpdate or React.memo.

2-4 Lift State Up:


In some cases, multiple components may need access to the same state.
Exploring the concept of “lifting state up,” here state is moved to a
common ancestor component, making it accessible to all the child
components that require it. This helps maintain data consistency and avoids
prop drilling.

48
2-4 Avoid Prop Drilling:
However, Prop drilling in React refers to the practice of passing down data
or functions through multiple layers of nested components in order to make
it available to a lower-level component that needs access to it.
Consequently, Prop drilling can lead to code that is difficult to read,
understand, and maintain. To avoid theis porblem, you can use contex
or Redux. This provides a more centralized way to manage data across
multiple components.

Conclusion for State and Props:


Understanding state and props is crucial for building interactive and
dynamic user interfaces in React. By mastering these concepts, you can
effectively manage and update data within your components, leading to
more robust and scalable applications.
Terminology:
• State: Data specific to a component that can change and affect
rendering.
• State Management: Managing and updating state across
components.
• Props: Immutable data passed from parent to child components.
• Prop Drilling: Passing data through many components to reach a
deeply nested one.
• Context API: Centralizes data management, avoiding prop drilling.
49
Dear learner: Choose the correct answer.

No. Question Answer


41 Which of the following is true about props?
a) Props are used to store mutable data.
b) Props are read-only and immutable.
c) Props are exclusive to class components.
d) Props can only be strings.

42 Which hook is used to handle state in functional


components?
a) useEffect
b) useState
c) useContext
d) useReducer

43 What does React.memo help with?


a) Creating class components
b) Avoiding prop drilling
c) Optimizing functional components' re-render
d) Defining CSS modules

50
44 Which of the following is true for CSS modules in
React?
a) CSS modules scope styles globally.
b) CSS modules scope styles locally to the component.
c) CSS modules must be defined inline.
d) CSS modules only work in functional components.

45 What is state in React?


a) A global store for managing data
b) An object that holds data specific to a component
c) A way to pass data between components
d) A function used to handle side effects

46 Which method is used to render components into the


DOM?
a) ReactDOM.render()
b) componentDidMount()
c) React.render()
d) ReactDOM.append()

47 Which of the following describes “prop drilling”?


a) Passing props from parent to child through
multiple layers
b) Using context to manage state

51
c) Fetching data from APIs
d) Creating reusable CSS modules

Dear learner: Complete the question.


No. Question Answer
48 Props are passed from the __________
component to the __________ component.
49 Side Effects in functional components is
managed using the __________ hook.

50 To apply inline styles in JSX, you use the


__________ attribute.
51 In class components, state is updated using the
__________ method.
52 When a component’s state changes, React will
__________ the component to reflect the new
state.
53 Props in React are __________, meaning they
cannot be changed by the child component.
54 You can avoid prop drilling by using the
__________ or __________ API.

(55 to 64) Match the correct answer from column A what suits column B
No Column (A) No. Column (B) Answer
1 Class Component A Immutable data passed from
parent to child.
2 State B A React hook used to manage
state in functional components.

52
3 Prop Drilling C A method used to update state in
class components.
4 ReactDOM.render() D Optimizes functional
components to avoid
unnecessary re-renders.
5 Functional Component E Renders a React component into
the DOM.
6 React.memo F A more complex component
using ES6 class syntax.
7 Props G A way to scope styles to a
particular component.
8 setState H Passing data through many
components to reach a deeply
nested one.
9 CSS Modules I A simple JavaScript function
that returns a React element.
10 useState J Data specific to a component
that can change over time.

53
Lesson 4
Name Hooks
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Define what Hooks are in React.
2. Recall the rules of using Hooks in React.
➢ Understanding
1. Explain the purpose of useState, useReducer,
useContext, and useEffect Hooks.
2. Describe how Hooks manage state and side effects in
functional components.
➢ Applying
1. Use useState to manage state in functional components.
2. Implement state management using useReducer for
complex state logic.
3. Utilize useContext to share state across components
without prop drilling.
4. Apply useEffect to handle component lifecycle events
like mounting, updating, and unmounting.
➢ Analyzing
1. Compare useState and useReducer for managing
component state.
2. Analyze how useEffect manages side effects in response
to state changes.
➢ Evaluating
1. Assess the benefits and limitations of using Hooks
versus class components for state management.
2. Evaluate the impact of using useContext for state
sharing on component structure and reusability.
3. Determine when to use useState versus useReducer
based on the complexity of state logic.
➢ Creating
1. Create functional components using various Hooks
(useState, useReducer, useContext, useEffect).
54
2. Implement a state-sharing mechanism using useContext
in a component tree.
3. Build a component that uses useEffect to handle
asynchronous data fetching or timers.

Code Description
TPK20 writing asynchronous code using various
Knowledge techniques
TPK21 Basic routing and calling a controller method
from a route
Code Description
Skill
TPC5.4 Using UI Framework (React)
TPC5.7 Using controllers and routes for APIs and URLs

55
Lesson Four: Hooks

IN THIS LESSON WE LEARN:


1. Introduction to Hooks
1. Rules of Hooks
2. React state management
1. What is it and why do you use it?
2. State in React
3. ReactJS built-in state management
3. The useState and useReducer Hooks
1. The useState Hook
2. The useReducer Hook
3. State management with the useContext Hook
4. useEffect Hook
1. Understanding useEffect
2. useEffect life cycle
3. few examples

56
Section 1 Introduction to Hooks
1-1 Introduction to Hooks
In React version 16.8, "Hooks" are introduced as tools that simplify
working with React, particularly when avoiding class components. They
enable special functions in functional components to manage state, handle
side effects, and more. React provides built-in Hooks like useState and
useEffect, and you can create custom Hooks. Hooks facilitate easy sharing
between components, allowing for code simplicity and flexibility without
requiring a complete code overhaul. They also encourage code modularity
by breaking it down into specific functions and enhance initial state
management through reducers.

1-2 Rules of Hooks


When working with React Hooks, there are two rules (the so-called rules of
Hooks) you must follow:
• Only call Hooks at the top level of component functions. Don't call
them inside of if statements, loops, or nested functions.
• Only call Hooks inside of React components or custom Hooks.
These rules exist because React Hooks won't work as intended if used in a
non-compliant way. Fortunately, React will generate a warning message if
you violate one of these rules, hence you will notice if you accidentally do
so.

Section 2 React state management


2-1 What is it and why to use it?
When it comes to React applications, state is an integral part of what makes
the application dynamic and interactive. Without state, applications would
be static and unresponsive to user input.
State management is the process of handling the state of an application
optimally. It is a crucial part of the development process.

57
2-2 State in React
The UI that is generated in a React app is a function of the state. To invoke
reactivity in an app, all we need to do is modify the state, and the React
library will take care of the rest. The graphic below sums up the
relationship between the application UX, state, and props in React:

2-3 ReactJS built-in state management


React has a variety of built-in features for state management, including the
useState and useReducer Hooks, as well as the Context API. Before
exploring third-party libraries for state management, let’s take a look at
these built-in features.

Section 3 The useState and useReducer and useContext Hooks


Both the useState and useReducer Hooks have a different approach for how
the state is updated. As mentioned above, both interfaces help us modify
the state. Beyond that, React takes care of all the heavy lifting required to
faithfully represent that state on the browser DOM. The graphic below
sums it up well:

58
3-1 The useState Hook
The useState Hook is the most basic API provided by React to interact with
state. To better understand how this hook works, let’s look at a counter app
example. First, let’s create the state:
const [count, setCount] = useState(0);
The above piece of code creates a state variable called count and a function
called setCount that can be used to update the state. The initial value of the
state is set to 0. Now, we’ll update the state by incrementing the value of
count by 1:
setCount(count + 1);
Finally, we’ll use the state:
<p>You clicked {count} times</p>
In this example, we used the state by displaying the value of count in the
UI.

59
3-2 The useReducer Hook
The useReducer Hook allows us to manage state by dispatching actions and
then responding to them in the reducer function. Again, we’ll use a counter
app example to understand how this hook works:
const [state, dispatch] = useReducer(reducerFunc, 0);
We call the useReducer Hook with the reducer function and the initial state
as arguments. It returns the current state and a dispatch function. Whenever
we need to update the state, we can call the dispatch function with an action
object:
dispatch({ type: 'INCREMENT' })
React then calls the reducer function with the action object. Here’s what a
common reducer function looks like:
function reducerFunc(state, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
case 'RESET':
return 0;
case 'SET':
return action.val;
}
}
At the end of this transaction, whatever the reducer function returns become
the new state and is accessible through the state variable. Here’s a sketch
that explains the flow of data in the useReducer Hook:
60
3-3 State management with the useContext Hook
Next, let’s look at how the useContext Hook comes into the picture for state
management. The general idea is to store a piece of data that components
can use, but the pattern and the use cases are different.
While useState and useReducer are used to manage the state that is scoped
to a component, useContext is used to manage state that is shared across
components. Its main purpose is to avoid prop drilling when a piece of state
is supposed to be accessed by a child component several levels down the
component tree. One of the primary use cases of context is to manage the
theme of the application. So, let’s look at the code for the same.
Inside a component near the top of the component tree, we’ll create the
context:
export const themeContext = createContext('light');
Notice how the newly created context object is exported from here. To use
that context, we’ll import it in a component down the tree:
import { useContext } from 'react';
import { ThemeContext } from './App.js';

61
export default function Button({ children }) {
const theme = useContext(ThemeContext);
// ...
}
But, for the above code to work, we need to first wrap the component tree
above this consumer component with the context Provider:
<ThemeContext.Provider value={theme}>
{children}
</ThemeContext.Provider>
With that in place, the consumer component will receive the value supplied
by the Provider. Whenever the value supplied to the Provider is updated,
the child below will be able to access that latest updated value.

Section 4 useEffect Hook


4-1 Understanding useEffect
To understand useEffect, you must understand React’s three lifestyle
methods: Mounting, when the component is first render; Updating, when
the component or state changes; and lastly, Unmounting.
useEffect as it says in the name defines a function (an effect) which will run
at one of the three points. To differentiate between the three. You have a
dependency array which defines when your effect will run.
For when the first page renders you would use an empty dependency array.
For when a state changes you would use a dependency array which would
look like this [state] and for when the component unmounts you would
have an empty dependency array which would have a return statement in it
which would run when it unmounts.
It would look like this:
useEffect(() => {}, [])
62
useEffect(() => {}, [state])
useEffect(() => {return () = {}}, [])

4-2 useEffect life cycle


useEffect is one of the most important hooks in react and is a way to handle
life cycle of the component in which it is present.
useEffect runs on every render of the component (i.e when a state variable
changes) and can also run every time a specific value changes that is
mentioned in it's dependency array.
useEffect also provides a very useful cleanup function which can be used
to remove any active listeners when the component changes

4-3 a few examples:


1. useEffect without dependency array
useEffect(() => {
/*the code you want to run has to be in here which will keep running
again and
again without stopping*/
})
2. useEffect with empty dependency array
useEffect(() => {
/*the code you want to run on every render has to be in here, the empty [] means
that the code will run everytime this component mounts*/
},[])
3. useEffect with state variables in dependency array
useEffect(() => {
/*the code you want to run on every render has to be in here, the dependency
array with state means that the code will run everytime this component mounts as
well as when these state variables change and the value will be captured by the

63
useEffect*/
},[state1,state2])
3. useEffect with state variables in dependency array and cleanup
useEffect(() => {
/*the code you want to run on every render has to be in here, the dependency
array with state means that the code will run everytime this component mounts as
well as when these state variables change and the value will be captured by the
useEffect*/
/*cleanup is used to remove any unwanted loops, intervals, listeners when the
component unmounts*/
return () => console.log("clean up");
},[state1,state2])

5. A complete example for useEffect


import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

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

useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);

return () => clearTimeout(timer)


}, []);

64
return <h1>I've rendered {count} times!</h1>;
}
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);

Terminology:
• Hooks: Functions that let you use state and other features in
functional components.
• useState: Adds state to functional components.
• useReducer: Manages complex state with a reducer function.
• useContext: Shares data across components without prop drilling.
• useEffect: Handles side effects like data fetching after rendering.

65
Dear Learner: Answer the following questions.

Question What is State Management?


65
Answer

Question What is Context API?


66
Answer

Dear learner: Put "True" in front of the correct statement and "False" in front
of the incorrect statement.

No. Question Answer


67 Hooks allow you to use state and lifecycle methods inside
class components.
68 You can call Hooks inside loops and nested functions.
69 React Router DOM is used for server-side routing in web
applications.
70 The useReducer hook is useful for managing more complex
state logic with actions.
71 useContext is used for prop drilling across multiple
components.
72 useEffect will execute after every render by default if no
dependency array is provided.

66
73 React Router allows you to navigate between different
components without refreshing the page.
74 The createBrowserRouter function is used to configure
routing in a React application.

Dear learner: Choose the correct answer.

No. Question Answer


75 What is the primary function of Hooks in React?
A. To replace CSS
B. To add state and lifecycle features to functional
components
C. To improve server-side rendering
D. To enhance form validations

76 Which of the following hooks is used for managing


component lifecycle events?
A. useState
B. useReducer
C. useEffect
D. useRef

67
77 Where should Hooks be called within a component?
A. Inside loops
B. Inside nested functions
C. At the top level of functional components
D. In the return statement of components

78 What is the role of the useState hook?


A. To fetch data from an API
B. To manage local state within a component
C. To navigate between routes
D. To define custom event listeners

79 What does the useReducer hook return?


A. A state and a function to update the state
B. A dispatch function and a reducer function
C. A state and a dispatch function
D. A function to create a new reducer

80 Which hook helps in managing shared state across


multiple components?
A. useState
B. useContext
C. useEffect

68
D. useMemo

81 What does the useEffect cleanup function handle?


A. DOM updates
B. Form submissions
C. Cleanup of resources like timers and listeners when
a component unmounts
D. Fetching data from APIs

82 Which of the following is a correct way to import


useParams from React Router?
A. import { useParams } from 'react';
B. import { useParams } from 'react-router-dom';
C. import { useParams } from 'router-dom';
D. import { useParams } from 'browser-router';

83 What does the createBrowserRouter function do?


A. Creates a new HTML page for routing
B. Defines route paths and components in React
applications
C. Fetches data from an API
D. Generates custom hooks for routing

69
84 How do you capture a dynamic URL parameter using
React Router?
A. useEffect
B. useParams
C. useState
D. useDispatch

70
Lesson 5
Name Manage App Location with React Router
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
3. Define client-side routing and server-side rendering.
4. Identify the main features of React Router.
➢ Understanding
4. Explain how React Router manages app location and
routing in single-page applications.
5. Describe the differences between server-side rendering
(SSR) and client-side rendering (CSR).
➢ Applying
7. Implement basic routing in a React application using
React Router.
8. Create navigation using Link components from react-
router-dom.
9. Use dynamic routes and URL parameters with
useParams.
10.Integrate server-side rendering (SSR) into a React
application.
➢ Analyzing
5. Analyze the benefits of client-side routing for a faster
user experience.
6. Compare SSR and CSR in terms of performance and
SEO friendliness.
➢ Evaluating
4. Assess the impact of using React Router on the
structure and behavior of a single-page application.
5. Evaluate the advantages and disadvantages of SSR and
CSR in different use cases.
➢ Creating
5. Develop a single-page application with multiple routes
using React Router.

71
6. Implement a navigation bar that uses Link components
to navigate between different routes.
7. Set up dynamic routing to handle URL parameters and
render specific components based on the URL.

Code Description
TPK21 Basic routing and calling a controller method
Knowledge from a route
TPK22 Analyze and solve common web applications
tasks by writing PHP programs
Code Description
TPC5.4 Using UI Framework (React)
Skill
TPC5.5 Creating an authentication system for your
application
TPC5.7 Using controllers and routes for APIs and URLs

72
Lesson Five: Manage App Location with React Router

IN THIS LESSON WE LEARN:


1. Introduction to Routing
1. Introduction
2. React Router DOM
2. React Router
3. Integrating Server-Side Rendering into a React App
4. ReactJS server-side rendering vs client-side rendering

73
Section 1 Introduction to Routing
1-1 Introduction
Client-side routing is one of the most important features to make use of
while developing single-page web applications. In web development,
routing describes the process by which a user clicks a link on a webpage
and is directed to a new page with different content and a unique URL. In
server-side routing, this would require making a request to the server and
navigating to a new HTML document. For single-page applications,
however, client-side routing can allow an app to update a URL and display
a new UI without making a server request for a new document. As you can
imagine, this leads to a faster, more streamlined user experience.

1-2 React Router DOM


The process of routing involves the direction of a user to a different page
based on their actions. One of the most frequent uses of ReactJS Router is
for developing Single Page Web Applications. The application uses React
Router to define multiple routes.
React Router is a standard library system that allows users to create routing
within React applications using the React Router package. It creates the
synchronous URL on the browser with web page data.
The main use of this framework is to develop single-page web applications
that maintain application structure and behavior. React Router plays a
crucial role in displaying multiple views, In a single page application. A
React application cannot show multiple views without React Router.
Many social media websites like Facebook and Instagram render multiple
views using React Router.

Section 2 React Router


One of the ways in which we can implement client-side routing in React is
using the React Router library. React Router allows us to link to a new
URL and conditionally render components based on that URL. In the
following example, we’ll be adding routes to a single-page application with
Home, About, and Login components.
74
The following example uses React Router v6 In order to use React Router
v6 in a React project, run the command “npm install react-router-dom” in
the root of your project directory. Then, to use routing in our app.
import React from 'react';
import { createBrowserRouter, RouterProvider } from 'react-router–-
dom';
import ProductList from './Components/ProductList';
import Cart from './Components/Cart';
import NotFound from './Components/Notfound';
import ProductContextProvider from './Context/ProductContext';
import ProductDetails from './Components/ProductDetails'
function App() {
return (
<Routes>
<Route path="/" element={<ProductList />} />
<Route path="/books" element={<BookList />} />
<Route path="/cart" element={<Cart />} />
<Route path="/product/:id" element={<ProductDetails />} />
<Route path="*" element={<NotFound />} />
</Routes> );
}
export default App;

in index.js file we wrap App component with Browser Router Component


import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root=ReactDOM.createRoot(document.getElementById("root"));
root.render( <React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>

75
);
}
Route Configuration in React Router v6
1. BrowserRouter Wrapper:
The BrowserRouter component is used to wrap the entire application,
enabling routing functionality. It ensures that the routes work as
expected across the app.
2. Routes and Route Components:
Routing is defined using a Routes component, which acts as a
container for all Route components. Each Route defines a specific
path and the corresponding component to render.
3. Base Route (/):
The base route (path="/") renders the ProductList component when
the user visits the root URL. This serves as the home page.
4. Dynamic Route (/product/:id):
The path="/product/:id" route is a dynamic route where :id acts as a
URL parameter. When a user visits a URL like /product/123, the
ProductDetails component is rendered, and the id value can be
accessed using the useParams hook.
5. Wildcard Route (*):
The path="*" is a fallback route that matches any undefined paths. It
renders the NotFound component, which is typically used to display a
404 error page.

Creating a NavBar
In our new NavBar component, we import the Link hook from react-router-
dom. To attach each Link to a URL path, we use the “to” prop, similar to
how the anchor element, <a> uses the href attribute in HTML.
import { Link } from "react-router-dom";
function NavBar() {

76
return (
// Match the route to the Link with the "to" prop
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/login">Login</Link>
);
}
export default NavBar

Navigation Links:
The <Link> component is used for navigation between routes without
refreshing the page. For example:
<Link to="/">Home</Link> navigates to the home page.
<Link to="/product/123">Product Details</Link> navigates to a specific
product.

Get Data From URL Using UseParams():


useParams is a hook from react-router-dom is used to access URL
parameters.
<div className="d-flex flex-column mt-4"<Link
to={`/product/${product.id}`} className="btn btn-primary btn-sm
mb-2">Details</Link>
</div>
This is a Link component from react-router-dom, which is used to navigate
to different routes within the application.
to={/product/${product.id}}:
• This dynamically generates a URL that includes the specific product's
ID. For example, if product.id is 5, the generated URL would be
/product/5.
• This URL will be used to navigate to the details page of the selected
product.
import React from 'react';
import { useParams } from 'react-router-dom';

77
function ProductDetails() {
const { id } = useParams();
return (
<>
<h1>{id}</h1>
</>
);
}
export default ProductDetails;
const { id } = useParams(); :
• The useParams hook extracts the id parameter from the URL. In the
context of your previous Link, this id corresponds to the product.id
passed in the URL.
• If the URL is /product/5, the id variable will be set to 5.
Section 3 ReactJS server-side rendering vs client-side rendering SSR
(Server-Side Rendering), CSR (Client-Side Rendering).

For a given website / web-application, you can use react either client-side,
server-side or both.

3-1 Client-Side

78
Over here, you are completely running ReactJS on the browser. This is the
simplest setup and includes most examples (including the ones on
http://reactjs.org). The initial HTML rendered by the server is a placeholder
and the entire UI is rendered in the browser once all your scripts load.
3-2 Server-Side

79
Think of ReactJS as a server-side templating engine here (like jade,
handlebars, etc...). The HTML rendered by the server contains the UI as it
should be, and you do not wait for any scripts to load. Your page can be
indexed by a search engine (if one does not execute any JavaScript).
Since the UI is rendered on the server, none of your event handlers would
work and there's no interactivity (you have a static page).

80
Terminology:
• Client-Side Routing: Navigating between pages in a single-page app
without reloading.
• React Router: Library for defining routes and navigation in React
apps.
• Server-Side Rendering (SSR): Server renders initial HTML for
faster load and better SEO.
• Client-Side Rendering (CSR): Browser renders app, slower initial
load but smoother interactions.

81
Dear learner: Complete the question.

No. Question Answer


85 React Router DOM is mainly used for routing in
_______.
86 The cleanup function in useEffect is used when a
component _______.
87 To manage more complex state logic, we use the
_______ hook in React.
88 The URL parameters in React Router can be
accessed using the _______ hook.
89 React application with multiple views requires the
use of _______ for routing.
90 To conditionally render components based on the
URL, we define _______ in React Router.
91 Every Route In react-router-Dom must have a
_______ to link with navbar Links.

82
(92 to 101) Match the correct answer from column A what suits column B
No Column (A) No. Column (B) Answer
1 useState hook A Shares state between
components
2 useReducer hook B Creates navigational links
3 useContext hook C Manages local component state
4 useEffect hook D Renders the routes
5 useParams hook E Handles side effects
6 createBrowserRouter F Handles complex state logic
7 RouterProvider G Configures routing
8 React Router H Placeholder for child
components
9 Link component I Enables client-side routing
10 Outlet component J Extracts URL parameters

83
Terminology:
• React.js (ReactJS): A JavaScript library by Facebook for building
UIs in single-page apps using reusable components.
• Virtual DOM: An in-memory version of the DOM used by ReactJS
to optimize rendering by updating only changed elements.
• JSX (JavaScript XML): A syntax for writing HTML-like code in
JavaScript files, transformed into standard JavaScript before running.
• React Native: A framework for building mobile apps for iOS,
Android, and Windows using native components.
• React Components: Reusable building blocks of a React app, acting
like custom HTML elements.
• Functional Components: Simple JavaScript functions that return
React elements. Ideal for static UI elements.
• Class Components: More complex components using ES6 classes.
They manage their own state and show inheritance.
• Props: Immutable data passed from parent to child components, used
to render dynamic content.
• State: Data specific to a component that can change and affect
rendering.
• State Management: Managing and updating state across
components.
• Props: Immutable data passed from parent to child components.
• Prop Drilling: Passing data through many components to reach a
deeply nested one.
• Context API: Centralizes data management, avoiding prop drilling.
• Hooks: Functions that let you use state and other features in
functional components.
• useState: Adds state to functional components.
• useReducer: Manages complex state with a reducer function.
• useContext: Shares data across components without prop drilling.
• useEffect: Handles side effects like data fetching after rendering.
• Client-Side Routing: Navigating between pages in a single-page app
without reloading.
84
• React Router: Library for defining routes and navigation in React
apps.
• Server-Side Rendering (SSR): Server renders initial HTML for
faster load and better SEO.
• Client-Side Rendering (CSR): Browser renders app, slower initial
load but smoother interactions.

85
Attention, students! Just a quick reminder: answers
don't just fall from the sky. Sometimes you've got to dig in and find them yourself. Think of it
as a treasure hunt, but with more brainpower and fewer pirate hats! Happy hunting!

No Answer
1 False
2 True
3 False
4 True
5 False
6 True
7 False
8 True
9 C
10 B
11 A
12 C
13 C
14 B
15 C
16 B
17 Single-page
18 Virtual
19 JavaScript
20 Curly braces {}
LESSON 2
21 Differences
22 Component-based
23 JSX
24 React Native
25 React.js is an open-source JavaScript library. It differs from
other frameworks by focusing the use of a Virtual DOM for
efficient UI rendering.

86
26 JSX is a syntax extension for JavaScript that allows developers
to write HTML-like code within JavaScript files.
27 React Native is used for building mobile applications, while
ReactJS is used for web applications .
28 Components are reusable pieces of code that define parts of the UI,
making the development of complex applications easier and more
modular.
29 True
30 False
31 True
32 False
33 True
34 False
35 True
36 True
37 True
38 False
39 C
40 B
LESSON 3
41 B
42 B
43 C
44 B
45 B
46 A
47 A
48 Parent, child.
49 Useeffect()
50 Style
51 setState()
52 re-render.
53 immutable.
54 Redux,Context
55 7

87
56 10
57 8
58 6
59 4
60 1
61 9
62 3
63 5
64 2
LESSON 4
65 Managing and updating state across components.
66 Managing and updating state across components.
67 False
68 False
69 False
70 True
71 False
72 True
73 True
74 True
75 B
76 C
77 C
78 B
79 C
80 B
81 C
82 B
83 B
84 B
LESSON 5
85 SPA
86 Unmounts
87 useReducer
88 useParams
88
89 React-router-dom
90 Routes
91 Path
92 3
93 9
94 1
95 7
96 4
97 2
98 6
99 10
100 8
101 5

89

You might also like