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

Lab 02-React Intro_ Web Tech 2

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

Lab 02-React Intro_ Web Tech 2

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

Web Technologies 2 Lab

Tsegamlak Molla
Web Technologies 2 Lab
Session 2

2 Web Technologies 2
React
Library
Introduction
Part 2

3 Web Technologies 2
React Library
• React is a popular front-end JavaScript library that allows developers
to build highly interactive user interfaces (UIs).
• It was developed by Facebook and is primarily focused on the View
aspect of web applications in the Model-View-Controller (MVC)
architecture.
• In other words, React is designed to render and manage the user
interface (UI) effectively by building and re-rendering reusable UI
components when data changes.

4 Web Technologies 2
Language used in React Library
• JSX is a syntax extension for JavaScript that allows you to write HTML-
like syntax within JavaScript code, hence it is not a standalone language
that you learn separately from JavaScript but rather a syntax that makes
writing React components easier and more intuitive.
• React commonly uses JSX (JavaScript XML) because of its readable and
declarative structure; though not a requirement for React.
• JSX essentially serves as syntactic sugar over React.createElement() calls
and makes it easier to visualize the UI.

5 Web Technologies 2
JSX (JavaScript XML)

• When you write JSX, it is not directly executable by the browser


because browsers do not understand JSX syntax.

• A compiler, like Babel, takes the JSX code and converts it to


standard JavaScript before the code is executed.

• During this compilation, each JSX element (<h1>Hello</h1>) is


turned into a call to React.createElement, which is what React needs
to generate the virtual DOM elements.

6 Web Technologies 2
JSX (JavaScript XML)
In JSX, you can embed JavaScript expressions using curly braces {}.
Syntax
const name = "John";
const element = <h1>Hello, {name}!</h1>;

Semantics
Curly Braces {}: Used to embed any valid JavaScript expression within JSX.

7 Web Technologies 2
JSX (JavaScript XML)

JavaScript expressions inside {} are evaluated and


inserted directly into the DOM.
• Example
const user = { firstName: "Jane", lastName: "Doe" };
const element = <h1>Hello, {user.firstName}
{user.lastName}!</h1>; // Contains: Hello, Jane Doe!
8 Web Technologies 2
Concepts in React
• Components: In React, the UI is broken down into small, reusable
pieces called components. Each component represents a part of the
UI (a button, form, menu, etc.) and can have its own logic, styling,
and functionality.
• State: State in React is the data that determines what gets
rendered. When state changes, React automatically re-renders the
components that rely on that state, making it easy to build
responsive and interactive interfaces.
9 Web Technologies 2
Concepts in React
• Props: Props are data passed to components, allowing components
to be reused with different values and configurations. This is
particularly helpful in an MVC setup, where different Views might
display similar elements with varied content.
• Virtual DOM: React uses a virtual DOM, which is an in-memory
representation of the actual DOM. When state changes, React
computes the minimal changes required and updates the DOM
efficiently, which improves performance.
10 Web Technologies 2
Concepts in React

• Component Lifecycle: Each React component goes through a


lifecycle (mounting, updating, and unmounting) that
developers can hook into to control the rendering behavior,
fetch data, or clean up when a component is removed from
the DOM.

11 Web Technologies 2
Component in React
A components in React involves HTML, CSS, and JavaScript:

• HTML (via JSX): Components use JSX to define the HTML-like structure of the
component. JSX allows developers to write HTML-like syntax within JavaScript,
which React then converts into actual HTML elements in the browser.

• CSS: Components often have styles to control their appearance. This can be
managed through traditional CSS files, CSS-in-JS solutions, or styled components,
making it possible to have encapsulated styles for each component.

• JavaScript: Components are written in JavaScript and can include logic to handle
user interactions, state management, and data fetching. JavaScript controls the
behavior of each component, like handling a button click or changing a form input.
12 Web Technologies 2
Component in React
A component:
Defines a part of the UI: Each component encapsulates some HTML
markup (structure), styling (CSS), and functionality (JavaScript) needed for
its part of the interface.
Renders UI based on data: Components can receive data through
props (input properties), and they can manage their own local state.
Re-renders when data changes: When a component’s state or props
change, it re-renders, updating the UI accordingly.

13 Web Technologies 2
Component in React
There are two main types of components in React:
• Functional Components: Functions that return JSX (a syntax extension
that looks like HTML) to define the UI. They’re simpler, focus on
rendering, and can use hooks (like useState and useEffect) for state and
lifecycle methods.
• Class Components: JavaScript classes that extend React.Component and
include a render method to return JSX. They can manage state and use
lifecycle methods but are generally less common in modern React; due
to the introduction of hooks.

14 Web Technologies 2
Functions Syntax in React
PascalCase for Component Names:
• Functional component names should follow PascalCase (every word
capitalized, no spaces), such as UserProfile or ContactForm.
• This convention helps React differentiate components from HTML elements,
which are always lowercase.

Example:
function HelloReactStudent() {
return <div>Welcome to your first React Exercise</div>;
}

15 Web Technologies 2
Functions Syntax in React
camelCase for Event Handlers and Utility Functions:
• Event handlers and helper functions use camelCase (first letter
lowercase, then capitalized words), like handleClick, fetchData, or calculateTotal.

Example:
function handleClick() {

console.log('Button clicked');

16 Web Technologies 2
Functions Syntax in React
• Parentheses (): Used to define the function parameters. If no
parameters are needed, use empty parentheses ().

• Curly Braces {}: Define the function body, where the code
logic resides.

• Return Statement:
• Functions can return JSX, which defines the component’s UI. They
could also return null or simply a value.
17 Web Technologies 2
Functions in React
• Returning JSX:
function Greeting() {
return <h1>Hello, World!</h1>;
}

• Returning Null:
function userGreeting (name) {
if(!name) return null;
return "Hello "+ name;
}

18 Web Technologies 2
Functions in React
• Returning a Value:
function sum(a, b) {

return a + b;

19 Web Technologies 2
New JavaScript ES6 Features for React

Some new features include:

• Arrow Functions, • Rest and Spread Operators,

• Array Methods • Objects

• Template Literals, • Classes

• Destructuring, • Promises and Async/Await

20 Web Technologies 2
Arrow Functions

Arrow functions offer a concise syntax for writing functions,


omitting the function keyword and using an arrow =>.

They also handle the this binding differently, capturing the this
value from the lexical scope where they are defined, making
them ideal for callbacks and functions used within objects.

21 Web Technologies 2
Arrow Functions
Single Parameter: Parentheses are optional if there’s only one parameter.

const square = x => x * x;

console.log(square(5)); // Output: 25

Multiple Parameters: Parentheses are required for multiple parameters.

const add = (a, b) => a + b;

console.log(add(3, 4)); // Output: 7

22 Web Technologies 2
Arrow Functions
No Parameters: Use empty parentheses when there are no parameters.
const greet = () => "Hello, World!";
console.log(greet()); // Output: Hello, World!

Multi-Line Body: Curly braces and an explicit return statement are required when
the function body spans multiple lines.
const sumSquares = (a, b) => {
const sum = a * a + b * b;
return sum;
};
console.log(sumSquares(2, 3)); // Output: 13

23 Web Technologies 2
Array Methods (map, filter, reduce)
map(): The map method creates a new array by applying a function to each element of the original array. It does not
mutate the original array.

Syntax:

Parameters:

• callback:

• A function that is called on each element of the array.

• Parameters of callback:

• currentValue: The current element being processed.

• index (optional): The index of the current element.

• array (optional): The original array being traversed.

• Return Value:

• A new array containing the results of calling the callback function on each element.

24 Web Technologies 2
Array Methods (map, filter, reduce)
map():

• Example: Creating a new array by applying a function to each


element of the original array.

25 Web Technologies 2
Array Methods (map, filter, reduce)
map():

• Example:

26 Web Technologies 2
Array Methods (map, filter, reduce)
filter(): The filter method creates a new array containing only the elements of the original array that satisfy a
given condition (predicate). It does not mutate the original array.

Syntax:

Parameters:

• callback:
• A function that tests each element for inclusion in the new array.

• Parameters of callback:
• currentValue: The current element being processed.

• index (optional): The index of the current element.

• array (optional): The original array being traversed.

• Return Value:
• A new array containing elements for which callback returns true.
27 Web Technologies 2
Array Methods (map, filter, reduce)
filter():

• Example: Creating a new array with elements that pass a


specified condition.

28 Web Technologies 2
Array Methods (map, filter, reduce)
reduce(): The reduce method reduces an array to a single value by executing a reducer function on each
element. It is a powerful method for aggregating array data.

Syntax:

Parameters:

• accumulator: Holds the accumulated result from previous iterations.

• currentValue: The current element being processed.

• currentIndex (optional): Index of the current element.

• array (optional): The array being processed.

• initialValue (optional): The initial value for the accumulator.

29 Web Technologies 2
Array Methods (map, filter, reduce)
reduce():

• Example: Reducing an array to a single value by applying a


function to each element and accumulating the result.

30 Web Technologies 2
Template Literals
• Template literals make it easier to construct strings, allowing
variables and expressions to be embedded directly.
Template literals use backticks (`) instead of quotes (' or ").
Embedded expressions are written within ${} and can include any JavaScript
expression (e.g., variable, arithmetic operation, function calls).

• Example:
let name = "Alice";
console.log(`Hello, ${name}!`); // Output: Hello, Alice!

31 Web Technologies 2
Destructuring
Definition:

• Destructuring is a convenient way to extract values from


arrays or properties from objects in JavaScript ES6 and assign
them to variables in a single statement.

• It simplifies working with complex data structures and makes


code more readable and concise.

32 Web Technologies 2
Destructuring
• Array Destructuring:

• Assign array elements to variables directly.

33 Web Technologies 2
Destructuring
• Array Destructuring:

• Default values can be assigned if the array is shorter than


expected.

34 Web Technologies 2
Destructuring
• Object Destructuring:

• Extract multiple properties from an object and assign them to


variables with matching names.

35 Web Technologies 2
Destructuring
• Object Destructuring:

• Destructuring can also handle nested properties and aliasing.

36 Web Technologies 2
Spread Operator
Array Spread:

• Used to copy or combine arrays, or to convert iterable


elements to an array of arguments.

37 Web Technologies 2
Spread Operator
Object Spread:

• Used to copy and merge objects.

38 Web Technologies 2
Spread Operator
Note:

• Spread Operator for Deep Copy: Spread only performs a


shallow copy, so nested objects aren’t deeply cloned.

• Default Values: Be cautious with default values in


destructuring; if the default is an expression, it’s only evaluated
if needed.

39 Web Technologies 2
Rest Operator

The Rest Operator is used to "collect" multiple elements or


properties into a single array or object. It is useful for handling a
variable number of arguments or for destructuring assignments.

40 Web Technologies 2
Rest Operator
Destructuring Arrays

• Rest operator can collect the remaining elements of an array


into a new array.

41 Web Technologies 2
Rest Operator
Destructuring Objects

• It can gather the remaining properties of an object into a new


object.

42 Web Technologies 2
Objects

An object is a collection of key-value pairs. Keys (also called


properties) can be strings or symbols, while values can be of any
type, including functions (which become methods when defined
inside objects).

43 Web Technologies 2
Objects in ES6
Object Literal Syntax

• Objects are typically created using curly braces {}.

44 Web Technologies 2
Objects in ES6
Methods in Objects
• Functions defined as part of an object are called methods. ES6 provides a concise way
to define methods.

45 Web Technologies 2
Classes in ES6

Classes in ES6 are syntactic sugar over JavaScript's


prototypal inheritance. They make it easier to define
and work with objects that share methods and
properties.

46 Web Technologies 2
Classes in ES6
Defining a Class
• The class keyword is used to define a class.

47 Web Technologies 2
Classes in ES6
Key Concepts

• Constructor:
• A special method that initializes an object.

• Called when an object is created using the new keyword.

• Methods:
• Functions inside a class.

• Automatically shared across all instances.

48 Web Technologies 2
Classes in ES6
Class Inheritance: Classes can extend other classes using the extends
keyword. The super() function is used to call the parent class's constructor
or methods.

49 Web Technologies 2
Classes in ES6
Static Methods:
Static methods belong to the class itself, not to its instances. They are
called directly on the class.

50 Web Technologies 2
Classes in ES6
Getters and Setters
• Getters and setters allow you to define computed properties or control access to
properties.

51 Web Technologies 2
Classes in ES6
Private Properties and Methods

• In ES6, private properties and methods can be denoted with a #.

52 Web Technologies 2
Handling Asynchronous Operations
JavaScript is a language that runs tasks one at a time
(synchronously), but in real-life programming, many tasks happen in
the background and take time to complete, like fetching data from a
server, reading files, or interacting with a database.

This is where asynchronous programming comes into play,


allowing us to handle time-consuming operations without freezing
the main flow of the program.

53 Web Technologies 2
Handling Asynchronous Operations
There are 2 ways, Promises and Async/Await, which are tools for
handling asynchronous operations in JavaScript.

They achieve the same goal allowing:


 non-blocking,

parallel execution

of tasks—but their syntax and flow differ significantly.

54 Web Technologies 2
Async/Await

• Async/Await is built on top of Promises and offers a


cleaner, more readable syntax for handling asynchronous
tasks.

• It allows developers to write asynchronous code that looks


like synchronous code.

55 Web Technologies 2
Async/Await
Syntax of Async/Await:

56 Web Technologies 2
Async/Await
Key Keywords in Async/Await

async: Declares a function as asynchronous, which


automatically returns a Promise.

await: Pauses the execution of the function until the Promise


is resolved or rejected, without blocking other executions.
The await keyword can only be used inside async functions.

57 Web Technologies 2
Async/Await
Flow of Async/Await
• The async function starts executing immediately but pauses at
the await keyword.
• The rest of the function waits until the awaited Promise resolves
or rejects.
• If resolved, the result is returned and execution continues.
• If rejected, an error is thrown and must be handled with a
try/catch block.
58 Web Technologies 2
Async/Await
Example:(Printing XML) const author =

const fetchAndDisplayXML = async ( ) => { books[i].getElementsByTagName("author")[0].textContent;

try {
console.log(`Book ${i + 1}: Title - ${title}, Author - ${author}`);
const response = await fetch("/public/Library_Instance.xml");
}
const xmlText = await response.text();
} catch (error) {
const parser = new DOMParser();
console.error("Error fetching or parsing XML:", error);
const xmlDoc = parser.parseFromString(xmlText,
"application/xml"); }

const books = };

xmlDoc.getElementsByTagName("book");

for (let i = 0; i < books.length; i++) { fetchAndDisplayXML(); // Calling the async function

const title =
books[i].getElementsByTagName("title")[0].textContent;

59 Web Technologies 2
Part 3 – React Next Level

60 Web Technologies 2

You might also like