0% found this document useful (0 votes)
24 views61 pages

FSD Unit2 Notes

Uploaded by

by4402
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)
24 views61 pages

FSD Unit2 Notes

Uploaded by

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

JAVASCRIPT OVERVIEW AND UNDERSTANDING JAVASCRIPT

JavaScript is a versatile, high-level programming language that is primarily known for its use in
web development. It was initially created to enhance web pages by enabling interactive and
dynamic content, but its capabilities have expanded significantly over the years. History and
Evolution
⮚ Creation:
JavaScript was created by Brendan Eich in 1995 while he was working at Netscape
Communications. It was originally called "Mocha," then "LiveScript" and finally “JavaScript”
⮚ Standardization:
JavaScript was standardized under the name ECMAScript (ES) by the European
Computer Manufacturers Association (ECMA) in 1997. Since then, multiple versions of
ECMAScript have been released, with ECMAScript 6 (ES6) in 2015 being a significant update.
Core Features:

⮚ Dynamic Typing: JavaScript is dynamically typed, meaning variable types are


determined at runtime.
⮚ First-Class Functions: Functions in JavaScript are first-class citizens, meaning they can
be assigned to variables, passed as arguments, and returned from other functions.
⮚ Prototype-Based Inheritance: JavaScript uses prototype-based inheritance, which is
different from classical inheritance models found in languages like Java or C++.
⮚ Event-Driven: JavaScript is event-driven, which makes it suitable for handling events like
user inputs, clicks, and other interactions in web applications.
Execution Environment
⮚ Client-Side (Browser): JavaScript is most commonly run in the browser, where it
interacts with the Document Object Model (DOM) to dynamically update web pages.
Popular browsers like Chrome, Firefox, and Safari have JavaScript engines (e.g., V8 in
Chrome) to execute JavaScript code.

⮚ Server-Side (Node.js): With the advent of Node.js, JavaScript can also be run on the
server side, allowing for the creation of full-stack applications using a single language.
Key Concepts

⮚ Variables and Data Types: JavaScript supports primitive data types like strings, numbers,
booleans, null, undefined, and the more complex types like objects and arrays.
⮚ Functions and Scope: Functions can be defined using function declarations, expressions,
or arrow functions. JavaScript also has lexical (block) scoping and closures.
⮚ Error Handling: Error handling in JavaScript is typically done using try...catch
blocksLibraries and Frameworks
⮚ Frontend Frameworks: Libraries and frameworks like React, Angular, and Vue.js are
built on JavaScript to create complex user interfaces.
⮚ Backend Frameworks: On the server side, frameworks like Express.js (for Node.js) are
commonly used to build APIs and handle server-side logic.
Ecosystem and Tools
⮚ Package Management: NPM (Node Package Manager) is the default package manager
for JavaScript, providing access to thousands of libraries and tools.
⮚ Build Tools: Tools like Webpack, Babel, and Parcel are used to bundle and transpile
JavaScript code, making it compatible with various browsers.
⮚ Testing: JavaScript has a rich ecosystem of testing libraries like Jest, Mocha, and Jasmine
for unit and integration testing.
Modern JavaScript (ES6 and Beyond)
⮚ ES6 Features: Includes significant updates like arrow functions, template literals, classes,
modules, let and const for variable declarations and destructuring.
⮚ Newer Features: Recent versions of ECMAScript have introduced features like optional
chaining, nullish coalescing, and advancements in asynchronous programming with
async/await.
Popular Use Cases
⮚ Web Development: JavaScript is essential for building interactive and responsive web
pages.
⮚ Mobile App Development: With frameworks like React Native, JavaScript can be used to
develop cross-platform mobile apps.
⮚ Server-Side Applications: Node.js allows JavaScript to be used for server-side scripting
and backend development.
⮚ Game Development: JavaScript is used in game development, particularly for web-based
games.
Future of JavaScript
JavaScript continues to evolve with regular updates to the ECMAScript standard. The
language's versatility and widespread use ensure that it remains a key technology in web and
software development for the foreseeable future.
Challenges
⮚ Browser Compatibility: Although modern browsers are more aligned, developers still
need to consider compatibility issues.
⮚ Security: JavaScript's ubiquity makes it a common target for security vulnerabilities,
requiring best practices in coding and security measures.
JavaScript is a foundational technology in modern web development and beyond, with a
constantly evolving ecosystem that supports a wide range of applications.
UNDERSTANDING DYNAMIC WEBSITES AND HTML 5 APPLICATIONS
The term dynamic refers to something active or something that motivates another person to
become active. A dynamic website is one that incorporates interactivity into its functionality and
design and that also motivates a user to take an action.
In web development, two types of scripting exist: server side and client side. Both types of
scripting which is, in fact, a form of computer programming are beyond the scope of these
lessons.
Some popular (and relatively easy-to-learn)
easy side scripting languages include the
server-side
following
owing (to learn more, visit the websites listed):
❖ Perl—www.perl.org
❖ PHP (PHP: Hypertext Preprocessor)
Preprocessor)—www.php.net
❖ Python—www.python.org
www.python.org
❖ Ruby—www.ruby-lang.org
lang.org
Including JavaScript in HTML
JavaScript code can live in one of two places in your files:
❖ In its own file with a .js extension
❖ Directly in your HTML files
Regardless of where your JavaScript lives, your browser learns of its existence through the use of
the <script></script> tag pair.
When you store your JavaScript in external files, it is referenced in this manner:
<script src="/path/to/script.js"></script>
These <script></script> tags are typically placed between the <head></head> tags
because, strictly speaking, they are not content that belongs in the <body> of the page.
Example of Using javascript to print some text

Output of Using javascript to print some text


Thinking Ahead to Developing HTML5
Applications
Although HTML5 is incredibly rich, the creation of highly interac tive HTML5 websites
interactive
and applications including mobile applications doesn’t happen in isolation. Interactivity comes
when HTML5 is paired with a client-side
client side language such as JavaScript, which then reaches back
into the server and talks to a server-side
server uage (PHP, Ruby, Python, and so on) through a
language
persistent connection called a web socket.
server side code that is (for example) talking to a
With this connection open and talking to some server-side
bundle of information that is
database or performing some calculation, the browser can relay a bundle
additionally processed by JavaScript and finally rendered in HTML5.
The depth of the technologies involved in HTML5 application creation is beyond the
standards compliant HTML5,
scope of these lessons, but the foundation you should have in standards-comp
CSS3, and JavaScript will serve you well if you begin to think outside the box of a basic website.
Getting Started with JavaScript
Programming
Statements
Statements are the basic units of a JavaScript program. A statement is a section of code
that performs a single action.
Combining Tasks with Functions
A function is a number of JavaScript statements that are treated as a single unit. A
statement that uses a function is referred to as a function call. For example, you might create a
function is called, a
function called alertMe, which produces an alert when called When this function
JavaScript alert pops up, and the text “I am alerting you” is displayed in a box, as shown in
Figure below

Variables
A variable is a container that can store a number, a string of text, or another value. For
atement creates a variable called fred and assigns it the value 27:
example, the following statement
var fred = 27;
JavaScript variables can contain numbers, text strings, and other values.
Understanding Objects
JavaScript also supports objects. Like variables, objects can store data—but
data they can
store two or more pieces of data at once. Using built in objects and their methods is fundamental
built-in
to JavaScript; it’s one of the ways the language works, by providing a predetermined set of
actions you can perform.
Conditionals
Although you can use event handlers to notify your script (and potentially the user) when
something happens, you might need to check certain conditions yourself as your script runs. For
example, you might want to validate on your own that a user entered a valid email address
addre in a
web form. JavaScript supports conditional statements, which enable you to answer questions. A
typical
conditional uses the if statement, as in this example:
Loops
Another useful feature of JavaScript—and
JavaScript and most other programming languages—is
languages the
capability
ability to create loops, or groups of statements that repeat a certain number of times. For
example, these statements display the same alert 10 times, greatly annoying the user:
for (i=1; i<=10; i++) { alert("Yes, it's yet another alert!"); }
he for statement is one of several statements JavaScript uses for loops.
The
Event Handlers
Each event handler is associated with a particular browser object, and you can specify the
event handler in the tag that defines the object. For example, images and text
te links have an event,
onmouseover, that happens when the mouse pointer moves over the object. Here is a typical
HTML image tag with an event handler:
<img src="button.gif" onmouseover="highlight();">

Output of a Simple Event Handler


JavaScript Syntax Rules
JavaScript is a simple language, but you do need to be careful to use its syntax the rules
that define how you use the language correctly.
Variable, Object, and Function Names
When you define your own variables, objects, or functions, you can chochoose their names.
Names can include uppercase letters, lowercase letters, numbers, and the underscore (_)
character. Names must begin with a letter or an underscore.
Case Sensitivity
Almost everything in JavaScript is case sensitive, which means you cannot use lowercase
and capital letters interchangeably. Here are a few general rules:
⮚ JavaScript keywords, such as for and if, are always lowercase.
⮚ Built-in
in objects, such as Math and Date,
Da are capitalized.
⮚ DOM object names are usually lowercase, but their methods are often a combination of
uppercase and lowercase sometimes called camel case. Usually uppercase letters are used
to start all words except for the first one, as in Spacing
⮚ vaScript ignores blank space (which programmers call whitespace). You can
JavaScript
include spaces and tabs within a line, or blank lines, without causing an error. Blank
space often makes a script more readable, so do not hesitate to use it.
Spacing
ores blank space (which programmers call whitespace). You can include
JavaScript ignores
spaces and tabs within a line, or blank lines, without causing an error. Blank space often makes a
script more readable, so do not hesitate to use it.

Best Practices for JavaScript


❖ Use comments liberally - Comments make your code easier for others to
understand and also easier for you to understand when you edit it later. They are also
useful for marking the major divisions of a script.
❖ Use a semicolon at the end of each statement and use only one statement per line -
Although you learned in this lesson that you do not have to end each statement with a
semicolon (if you use a new line), using semicolons and only one statement per line will
make your scripts easier to read and also easier to debug.
❖ Use external JavaScript files whenever possible - Separating JavaScript into external files
helps pages load more quickly and also encourages you to write modular scripts that can
be reused.
❖ Avoid being browser specific - As you learn more about JavaScript, you’ll learn some
features that work in only one browser. Avoid such features unless absolutely necessary
and always test your code in more than one browser to ensure that everything works.
❖ Keep JavaScript optional - Don’t use JavaScript to perform an essential function on your
site (for example, for the primary navigation links). Whenever possible, users without
JavaScript should be able to use your site, although it might not be quite as attractive or
convenient without the JavaScript. This strategy is known as progressive enhancement.
Understanding JSON
Although JSON, or JavaScript Object Notation, is not a part of the core JavaScript
language, using it is in fact a common way to structure and store information either used by or
created by JavaScript-based functionality on the client side. Now is a good time to familiarize
yourself with JSON (pronounced “Jason”) and some of its uses.
Working with the Document Object
Model (DOM)

One advantage of JavaScript over plain HTML is that client-side JavaScript scripts can
manipulate the web browser and documents (including their contents) right in the browser after
the content has been loaded. Your script can load a new page into the browser, work with parts
of the browser window and the loaded document, open new windows, and even modify text
within the page all dynamically, without requiring additional requests to a server.
using JavaScript.
Example of a HTML document that displays its last modified date using
Output of a HTML document that displays its last modified date using JavaScript.
Using Links
Using Anchors

Example of A Web Page That Uses JavaScript to Include Back and Go Forward Buttons
to Include Back and Go Forward Buttons
Output of A Web Page That Uses JavaScript to
Hiding and Showing Objects
JavaScript Variables, Strings, and Arrays
1. JavaScript Variables

Variables are used to store data values in JavaScript.

Types of variable declarations:


1. var – Function-scoped, can be re-declared and updated.
2. let – Block-scoped, can be updated but not re-declared in the same
scope.
3. const – Block-scoped, cannot be updated or re-declared.

Example:
var x = 10; // var variable
let y = 20; // let variable
const z = 30; // constant variable

2. JavaScript Strings

A string is a sequence of characters used to represent text.

Creating strings:
let str1 = "Hello";

let str2 = 'World';

let str3 = `Hello ${str2}`; // Template literal


Common string methods:
- length → str.length
- toUpperCase() → str.toUpperCase()

- toLowerCase() → str.toLowerCase()

- substring(start, end) → str.substring(0, 5)


- indexOf("text") → str.indexOf("o")
- split(" ") → str.split(" ")

- trim() → str.trim()

Example:

let message = " Hello JavaScript ";


console.log(message.trim().toUpperCase()); // "HELLO

JAVASCRIPT"

3. JavaScript Arrays

Arrays are used to store multiple values in a single variable.

Creating arrays:
let arr1 = [1, 2, 3, 4];
let arr2 = new Array("Apple", "Banana", "Cherry");

Accessing elements:
console.log(arr1[0]); // 1

Common array methods:


- length → arr.length
- push(item) → arr.push("Mango")

- pop() → arr.pop()

- shift() → arr.shift()
- unshift(item) → arr.unshift("Lemon")

- indexOf(item) → arr.indexOf("Banana")
- join(",") → arr.join(", ")

- slice(start, end) → arr.slice(1, 3)


- splice(index, count) → arr.splice(2, 1)

- forEach(callback) → arr.forEach(item => console.log(item))


- map(callback) → arr.map(x => x * 2)

Example:

let fruits = ["Apple", "Banana", "Cherry"];


fruits.push("Mango");

console.log(fruits); // ["Apple", "Banana", "Cherry", "Mango"]


JavaScript: Controlling Flow and Events
1. Controlling Flow with Conditions

Conditions allow decision-making in JavaScript programs. They help execute certain blocks of
code based on logical tests.

Types of Conditional Statements:

1. if Statement:
if (condition) {
// code runs if condition is true
}

2. if...else Statement:
if (condition) {
// code if true
} else {
// code if false
}

3. if...else if...else Ladder:


if (condition1) {
// code if condition1 true
} else if (condition2) {
// code if condition2 true
} else {
// code if none true
}

4. switch Statement:
switch(expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}

2. Loops

Loops allow executing a block of code multiple times.

Types of Loops:

1. for Loop:
for (let i = 0; i < 5; i++) {
console.log(i);
}

2. while Loop:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}

3. do...while Loop:
let j = 0;
do {
console.log(j);
j++;
} while (j < 5);

4. for...of Loop (for arrays, strings, collections):


let arr = [10, 20, 30];
for (let num of arr) {
console.log(num);
}
5. for...in Loop (for object properties):
let obj = {name: "Alice", age: 22};
for (let key in obj) {
console.log(key + ": " + obj[key]);
}

3. Responding to Events

Events are actions that happen in the browser (like clicks, keypress, mouse movements).
JavaScript can respond to these events.

Common Event Types:


- onclick → when user clicks
- onmouseover → when mouse hovers
- onkeydown → when a key is pressed
- onchange → when value changes
- onload → when page finishes loading

Example:
<button onclick="alert('Button clicked!')">Click Me</button>

Using addEventListener():
document.getElementById("btn").addEventListener("click", function() {
alert("Button was clicked!");
});

4. Using Windows

The window object represents the browser window and is the global object in JavaScript.
Common Methods of window:
- alert("message") → shows alert box
- prompt("Enter your name") → takes input from user
- confirm("Are you sure?") → returns true/false
- setTimeout(function, milliseconds) → runs code after delay
- setInterval(function, milliseconds) → runs code repeatedly

Example:
alert("Welcome to JavaScript!");
let name = prompt("Enter your name:");
if (confirm("Do you want to continue?")) {
console.log("User continued");
} else {
console.log("User canceled");
}
JavaScript Best Practices and Using Third-Party Libraries & Frameworks
1. JavaScript Best Practices

Writing clean, efficient, and maintainable JavaScript code requires following best practices.
These help improve readability, reduce bugs, and make collaboration easier.

Best Practices:

1. Use Meaningful Variable and Function Names


- Example: let userName instead of let x

2. Prefer const and let over var


- const for values that do not change
- let for block-scoped variables

3. Use Strict Equality (===) instead of Loose Equality (==)


- "===" checks both value and type

4. Avoid Global Variables


- Global variables can cause conflicts; prefer block or function scope

5. Write Modular Code


- Break code into smaller, reusable functions or modules

6. Comment and Document Code


- Write meaningful comments to explain complex logic

7. Handle Errors Properly


- Use try...catch blocks where errors may occur

8. Use Consistent Indentation and Formatting


- Improves readability and teamwork

9. Avoid Deep Nesting


- Refactor code to prevent complexity

10. Optimize Performance


- Use efficient loops, caching, and asynchronous operations where needed

2. Using Third-Party JavaScript Libraries and Frameworks

JavaScript libraries and frameworks provide pre-written code to speed up development, add
functionality, and improve maintainability.

1. What are Libraries?


- Libraries are collections of functions that help perform common tasks more easily.
- Example: jQuery, Lodash, D3.js

2. What are Frameworks?


- Frameworks provide a structured way to build applications with pre-defined rules.
- Example: React, Angular, Vue.js

3. Benefits of Using Libraries/Frameworks:


- Faster development
- Better performance optimization
- Large community support
- Reusable and tested code

4. Commonly Used JavaScript Libraries:


- jQuery → Simplifies DOM manipulation and AJAX
- Lodash → Provides utility functions for arrays, objects, and strings
- D3.js → Powerful library for data visualization

5. Commonly Used JavaScript Frameworks:


- React → Library/framework for building user interfaces
- Angular → Full-fledged framework for single-page applications
- Vue.js → Lightweight framework for UI development

6. Installing Third-Party Libraries:


- Using npm: npm install library-name
- Using CDN: <script src="library_url"></script>

Example (React with CDN):


<script src="https://unpkg.com/react@17/umd/react.development.js"></script>

Example (jQuery):
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

7. Best Practices for Using Third-Party Code:


- Use only trusted libraries from reliable sources
- Keep dependencies updated
- Avoid unnecessary libraries to reduce project size
- Read documentation before using
- Regularly check for security vulnerabilities
REACTjs

React is a JavaScript library for creating interactive user interfaces using components.

React in response to its need to be able to efficiently update websites in response to events. Events that
can trigger updates in websites include user input, new data coming into the application from other
websites and data sources,

and data coming into the application from sensors (such as location data from GPS chips).

The method of updating a user interface in response to data changes is called reactive programming.

UI LAYER

Web applications typically are built and described using the Model- View-Controller (MVC) pattern. The
Model in MVC is the data layer, the Controller facilitates communication with the data layer, and the
View is what the user sees and interacts with. In an MVC application, the View sends input to the
Controller, which passes data between the data layer and the View. React is only concerned with the V
in MVC. It takes data as input and presents it to the user in some form.

React itself doesn’t care whether the user is using a mobile phone, a tablet, a desktop web browser, a
screen reader, a command-line interface, or any other kind of device or interface that may be invented
in the future. React just renders components. How those components get presented to the user is up to
a separate library.

The library that handles rendering of React components in web browsers is called ReactDOM. If you
want to render React elements to native mobile apps, you use React Native. If you want to render

React components to static HTML, you can use ReactDOMServer.

ReactDOM has a number of functions for interfacing between React and web browsers, but the one that
every React application makes use of is called ReactDOM.render. Figure 2-2 illustrates the relationship
between React, ReactDOM, and a web browser.
VIRTUAL DOM

DOM, is a web browser’s internal representation of a web page. It


The Document Object Model, or DOM,
converts HTML, styles, and content into nodes that can be operated on using JavaScript.

Here’s how virtual DOM works:

1. A programmer writes React code to render a user interface, which resul


results
ts in a single React element
being returned.

2. ReactDOM’s render method creates a lightweight and simplified representation of the React element
in memory (this is the Virtual DOM).

3. ReactDOM listens for events that require changes to the web page.

4. The
he ReactDOM.render method creates a new in memory representation of the web page.
in-memory

5. The ReactDOM library compares the new Virtual DOM representation of the web page to the previous
Virtual DOM representation and calculates the difference between the two. This process is called
reconciliation.

6. ReactDOM applies just the minimal set of changes to the browser DOM in the most efficient way that
it can and using the most efficient batching and timing of changes.
JSX

JSX is an XML-based
based syntax extension to JavaScript.JSX is an integral part of how every React developer writes
components because it makes writing components so much easier and has no negative impact in terms of
performance or functionality.

How JSX Works

React uses JSX elements to represent custom components (which are also known as user-
user defined
components). If you create a component named SearchInput, you can make use of that component in other
components by using a JSX element named SearchInput,
Compilation vs. Transpilation

Compilation of React applications is somewhat different from how programmers of truly “compiled”
languages (like C++ or Java) understand compilation. In compiled languages, the code that you write is
converted into low-level code that
hat can be understood by the computer’s software interpreter. This low
low-
level code is called bytecode.

When React applications are compiled, on the other hand, they’re converted from one version of
React compilation process doesn’t actually
JavaScript to another version of JavaScript. Because the React
create bytecode, a more technically correct word for what happens is transpilation.

JSX Transform

One of the steps in the transpilation of React code is the JSX Transform. The JSX Transform is a process
in which thee transpiler takes JSX code (which isn’t natively understood by web browsers) and converts it
into plain JavaScript (which is natively understood by web browsers).

Introducing Babel

The tool we use for transpilation in JavaScript is called Babel. Babel is integrated into Create React App
and is an automatic part of compiling a React app built with Create React App.

Conditionals in JSX

Oftentimes, a component needs to output different subcomponents, or hide certain components, based
ions or the values of variables. We call this conditional rendering.
on the results of expressions

There are three ways to write conditional statements in JavaScript, and you may use any of these to do
conditional rendering.

Conditional Rendering with if/else and Element Variables

JSX elements can be assigned to variables, and these variables can be substituted for the elements
inside a component’s return statement, as shown in Listing 3
3-8
Conditional Rendering with the && Operator

Rather than having your conditional logic outside of the return statement, you can write it inline by
using the logical AND operator, &&. The && operator evaluates the expressions on its left and right. If
both expressions evaluate to a Boolean true, the && will return the one on the right. If either side o
of the
&& operator is false, then a value of false will be returned.

By applying this fact, you can conditionally return an expression from the right side of && if the left side
of && is true.

This can be a little confusing at first. Take a look at Listing 3-10.


10. This code will render the Header
component if loggedIn evaluates to true.

Conditional Rendering with the Conditional Operator

The conditional operator is a way to combine the simplicity and conciseness of inline conditional
ty to have an else case that element variables combined with if and else gives us.
rendering with the ability

Listing 3-11
11 shows an example of using the conditional operator.
React Fragments

Although it’s quite common to see multiple elements wrapped with a div element or another element
for the purpose of returning a single JSX element, adding div elements just for the sake of eliminating
errors in your code, rather than to add necessary meaning or structure to your code, creates code bloat
and decreases the accessibility of your code.

built in React.Fragment
To prevent the introduction of unnecessary elements, you can use the built-in
component. React.Fragment wraps your JSX into a single JSX element, but doesn’t return any HTML.

You can use the React.Fragment component in one of three ways:

1. By using dot notation: <React.Fragment></React.Fragment>

2. By importing Fragment from the react library using curly braces

3. By using its short syntax, which is just a nameless element: < > < / >

WHAT IS A COMPONENT?

Components are the building blocks of React applications. A React component is a function or a
JavaScript class that optionally accepts data and returns a React element that describes some piece of
the user interface. A React user interface is made up of a hierarchy of components that build up to a
single component (called the root component) that is rendered in the web browser.

COMPONENTS VS. ELEMENTS

Before we talk about components, it’s important to understand the relationship between components
and elements in React.
Components Define Elements

The job of a component is to return an element.

Each component within an application has a unique name, which is how you use it. The component
name becomes the name of the React element when you include a component in another component,
as shown in Listing 4‑

Attributes vs. Props

In markup languages (such as XML and HTML), attributes define properties or characteristics of the
element, and are specified using the name=value format.

Because JSX is an XML markup lan guage, JSX elements can have attributes, and there’s no limit to the
language,
number of attributes that a single JSX element can have.

In markup languages (such as XML and HTML), attributes define properties or characteristics of the
element, and are specified usingg the name=value format.

Because JSX is an XML markup language, JSX elements can have attributes, and there’s no limit to the
number of attributes that a single JSX element can have.

Passing Props

Attributes that you write in JSX elements are passed to the component represented by the element as
properties, or props for short. You can access props inside the component using the component’s props
object.

To illustrate how props are used for passing data between components, I’ll use the example of a
component called Farms, which includes multiple instances of the Farm component, as shown in Listing
4‑5.
‑5. Props that you pass into the Farm component are what make it possible for the generic Farm
component to represent any farm.

Note that a string can be passed into


into a component by surrounding it with quotes, and that any other
type of data can be passed to a component by using curly braces to indicate that the value should be
treated as JavaScript.

Accessing Props

Once values have been passed as props, you can access


access that data inside the component. Listing 4‑6
4

shows the Farm component and how it makes use of the data passed into it.

USER- DEFINED COMPONENTS

Have you ever thought that it would be awesome if you weren’t just limited to the standard set of HTML
ments? What if you could, for example, make an element called PrintPageButton that you could use
elements?
anywhere that you need to display a functional print button in your app? Or what if you had an element
called Tax that would calculate and display the taxes in your online store’s shopping cart?
Essentially, this is what React components enable through custom components. Custom components,
also known as user‑ defined components, are the components that you make by putting together
builtin components and other custom components.

The possibilities for custom components are infinite. Even better, if you design your components to be
reusable, you can reuse components not only inside of a single React application, but across any number
of React applications. There are even hundreds of open source libraries of custom components created
by other developers that you can repurpose inside your own apps.

Writing useful and reusable React components can sometimes require considerable work up front, but
the benefits of writing them the right way are that you can reduce work for yourself overall and make
apps that are sturdier and more dependable.

In the rest of this chapter, you’ll learn about writing custom components and putting them together to
build robust user interfaces.

TYPES OF COMPONENTS

React components can be written in two different ways: by using JavaScript classes or by using
JavaScript functions.

Class Components

Classes were new to JavaScript when React was first released. The early versions of the React library had
a function called React.createClass, which was the only way to create components. To use
React.createClass, you could pass an object containing the component’s properties as a parameter to
the function and the result would be a React component.

In one of the bigger changes made to React in its lifetime so far, React.createClass was deprecated as of
React 15.5.

You can still use createClass if you need to by installing the create- react- class package. Listing 4‑8
shows the code for a component created using createClass.
Listing 4‑9 showss how to write the component from Listing 4‑8
4‑8 using a class that extends

React.Component

68 ❘ CHAPTER 4 All About Components

Stepping through a React Class Component

Once you have an understanding of how prototypal inheritance works in JavaScript, and you know that
classes are just another way to use function constructors, creating React components using the class
method is actually quite easy and it becomes a powerful tool in your React toolbox.

React.Component

React.Component is the base class for every class component that you’ll make. It defines a number of
methods, lifecycle methods, class properties, and instance properties that you can make use of and
extend in your components.

Importing React.Component
Because a custom component is a subclass of React.Component, any file that defines a class component
(or more than one class component, in the case of a library) must start by importing React.

by importing the entire React library, or by importing individual objects from the React library.

Here’s the import statement for importing the entire React library:

import React from 'react';

This import is called a “default import.

You potentially save a few keystrokes inside your component by using a named import to import the

Component class specifically, as shown here:

import {Component} from 'react';

The Class Header

If you import the entire library into your new component module, the first line of your new component
will be as follows (assuming that your component is named MyComponent):

class MyComponent extends React.Component{

If you import Component using a named import, the header of your new component will look

like this:

class MyComponent extends Component{

The Constructor Function

Next up is the constructor. If you include a constructor in your class, it will run one time when an
instance of the class is created. The constructor is where you will bind event handler functions to the
instance of the class and set up the local state for the instance.

A typical constructor in a component looks like this:

constructor(props) {

super(props);

this.state = {

score: 0;

userInput: ''

}
this.saveUserInput = this.saveUserInput.bind(this);

this.updateScore = this.updateScore.bind(this);

After the constructor header and the call to the super function, this constructor has two

purposes—it initializes the component instance’s state, and it binds event handler methods to the

component instance.

Function Components

The function component was created to simplify the creation of React components. To illustrate how
much easier writing a function component can be than a class component, consider the simple To Do
List example class in Listing 4‑18.

LISTING 4- 18: A typical class component

import React from 'react';

class ToDoClass extends React.Component{

constructor(props){

super(props);

this.state = {

item: '',

todolist: []

this.handleSubmit = this.handleSubmit.bind(this);

this.handleChange = this.handleChange.bind(this);

}
FIGURE 4- 3: The result of rendering FigureList

Types of Components ❘ 77

handleSubmit(e){

e.preventDefault();

const list = [...this.state.todolist, this.state.item];

this.setState({

todolist:list

})

handleChange(e){

this.setState({item:e.target.value});

render(){

const currentTodos = this.state.todolist.map(

(todo,index)=><p key={index}>{todo}</p>);

return (

<form onSubmit={this.handleSubmit}>

<input type="text"

id="todoitem"

value={this.state.item}

onChange={this.handleChange}

placeholder="what to do?" />

<button type="submit">

Add

</button>
{currentTodos}

</form>

);

export default ToDoClas

Listing 4‑19 shows how you can write a component that does the same thing as the class in Listing 4‑18
using a function component.

LISTING 4- 19: A typical function component

import React,{useState} from 'react';

function ToDoFunction(props){

const [item,setItem] = useState('');

const [todolist,setTodoList] = useState([]);

const handleSubmit = (e)=>{

e.preventDefault();

const list = [...todolist, item];

setTodoList(list)

const currentTodos = todolist.map((todo,index)=><p key={index}>{todo}</p>);

return (

<form onSubmit={handleSubmit}>

<input type="text"

id="todoitem"

value={item}

onChange={(e)=>{setItem(e.target.value)}}
placeholder="what to do?" />

<button type="submit">

Add

</button>

{currentTodos}

</form>

);

export default ToDoFunction;

What Are Function Components?

Function components are JavaScript functions that return React elements.

When they were first introduced into React, function components were a simplified way to write certain
kinds of components called “stateless functional components.” Stateless functional components are also
known as “dumb components” or “presentational components.”

Stateless functional components simply accept props from their parent and return a piece of the user
interface. They don’t perform additional operations, such as fetching and posting data, and they don’t
have their own internal state data.

Hooks allow function components to do most of the things that class components can do, such as
interacting with data stores and using state. The result is that function components have now become
the primary way that

most React components are written.

React’s official documentation states that class components will continue to be supported for the
foreseeable future. At this point, however, no one can foresee how much longer they’ll be necessary. If
you’re currently writing class components, there’s no need to convert them to function components.
THE COMPONENT LIFECYCLE

During the time when a React application is running, components become active, do their thing,

and are destroyed. At each stage in the life of a component, certain events are fired and methods are

invoked. These events and methods make up the component lif


lifecycle.

The stages of a component’s life are:

➤➤Mounting: Mounting is where a component is constructed using the props passed into it and

the default state, and the JSX returned by the component is rendered.

➤➤Updating: Updating happens when the state of the component changes and the component is

re‑ rendered.

➤➤Unmounting: Unmounting is the end of the component lifecycle, when the component is

removed from the active application.

➤➤Error handling: The error handling methods run when an error happens during a compo‑
compo

nent’s lifecycle.
The following sections will examine the four stages of the component lifecycle and then will explore

how you can avoid errors and improve performance with the lifecycle as well.

Mounting

The mounting stage includes everything from when a component is first constructed until it is

inserted into the DOM. During the mounting lifecycle stage, the following methods run, in this order:

➤➤constructor

➤➤static getDerivedStateFromProps

➤➤render

➤➤componentDidMount

constructor()

You’ve already learned about the constructor. This is the method that automatically runs in an

instance of a class when it’s created. In a React component, it may include a call to the super method,

initialization of the component’s state object, and binding of event handlers.

static getDerivedStateFromProps

This method is a static method, meaning that it doesn’t have access to the this keyword. The pur‑

pose of getDerivedStateFromProps is to check whether the props that the component uses have

changed and to use the new props to update the state. This method runs both during the mounting

stage as well as during the updating stage.

render

Like getDerivedStateFromProps, the render method also runs once during the mounting stage.

After mounting, render runs every time the component updates. This is the method that generates

the JSX output of your component, and it’s the only required method in a class component.

componentDidMount()

The componentDidMount method runs when the component has finished mounting and has been

inserted in the browser DOM. This is the point at which it’s safe to do things that depend on DOM
nodes, or to fetch remote data.

Updating

After your component has mounted, the updating lifecycle methods start running. React components

update their data and re‑render in response to changes to the state object made using the setState

function. Every time a component updates, the following methods run, in this order:

➤➤static getDerivedStateFromProps

➤➤shouldComponentUpdate

HOW EVENTS WORK IN REACT

To put it simply, listening for events in a React component and handling events is done similarly

to how HTML event attributes trigger actions in a browser.

In HTML, it’s possible to use event attributes to call JavaScript functions. These event attributes have
names starting with “on” and they take a function call as their value. For example, the HTML onsubmit
event attribute can be used with the <form> element to invoke a function when the form is submitted.
Listing 7‑1 shows an example of using the HTML onsubmit attribute. This example assumes that a
JavaScript function named validate() has been defined

or imported elsewhere in the HTML file.

200 ❘ CHAPTER 7 EvEnts

LISTING 7- 1: Using an event attribute in HTML

<form id="signup-form" onsubmit="validate()">

<input type="text" id="email">

<input type="text" id="fullname">

<input type="submit">

</form>

Because HTML event attributes violate the “separation of concerns” rule that says markup and scripts
should be kept separate, it’s generally not a good practice to rely on them too heavily in web apps.
Instead, most JavaScript programmers use the addEventListener DOM method to attach event listeners
to HTML elements, as shown in Listing 7‑2.

LISTING 7- 2: Using addEventListener


<html>

<head>

<script>

function validate(e){

//do something here

</script>

</head>

<body>

<form id="signup-form">

<input type="text" id="email">

<input type="text" id="fullname">

<input type="submit">

</form>

<script>

document.getElementById("signup-form").addEventListener("submit",validate);

</script>

</body>

</html>
THE EVENT OBJECT

When an event happens in React, it triggers an event in the DOM. This, in turn, creates an instance of
the Event object, which triggers the creation of a SyntheticEvent object in React. This is what we mean
by SyntheticEvent being a wrapper around native DOM events.

The Event object contains the properties and methods that are common to all events. The most
important of these base Event properties and methods are the following:

➤➤Event.cancelable indicates whether an event can be canceled. Canceling an event prevents

the event from happening. Canceling events is useful when you want to prevent a user from clicking
something or to prevent a form element from submitting a form, for example.

➤➤Event.target references the object onto which the event was originally dispatched (such as an
element that was clicked or a form input that was typed into).

➤➤Event.type contains the name of the event, such as click, change, load, mouseover, and so forth.

➤➤Event.preventDefault cancels an event if it’s cancelable.

The wrapper that React creates around the JavaScript Event object is named SyntheticBaseEvent.

To access the properties and methods of the SyntheticBaseEvent object, specify a parameter in the
function definition for your event handler. The SyntheticBaseEvent object will take the name of this
parameter inside the function. It’s a standard practice for this parameter to be named either event or
simply e, but there’s no restriction in React or JavaScript on what valid JavaScript variable name you give
it.

LISTING 7- 4: Viewing the properties of the Event object

function EventProps(){

const logClick=(e)=>{

console.dir(e);

return(

<button onClick={logClick}>Click Me</button>

}
export default EventProps;

EVENT HANDLER FUNCTIONS

detected an event, you can write a function that will take some action
Once your React component has detected
in response to the event. This function is called an event handler function.

Writing Inline Event Handlers

An inline event handler is an anonymous function that’s written as the value of an event listener
attribute. Inline event handlers are often used as wrappers for calling another function that’s defined
outside of the return statement. They may also be used for performing simple tasks that perhaps don’t
warrant the creation of a full event
vent handler function.

LISTING 7- 5: Using an inline event handler to show an alert

function WarningButton(){

return (

<button onClick={()=>{alert('Are you sure?');}}>Don't Click Here</button>

);

export default WarningButton;

It’s possible to call multiple functions or execute a block of code from inside an inline event handler,
but there are several reasons for not using inline event handlers for complex code:

1. Inline event handlers aren’t reusable.

2. Inline event handlers can be difficult to read and they reduce the organization of your code.

HTML form

HTML form elements are what make it possible for web applications to gather user input. React has
built- in HTML DOM components that create native HTML form elements. The built- in React
components that create HTML form elements behave somewhat differently from native HTML form
elements in some important ways, :

LISTING 8- 1: Omiting the value attribute creates an uncontrolled input

function SignUp(props){

return(

<form>

<input type="text" name="emailAddress" />

<button>Sign up for our newsletter</button>

</form>

export default SignUp;


Controlling an Input in a Function Component

Listing 8-3 shows a controlled text input that updates using one- way data flow in a function

component.

LISTING 8- 3: Updating an input element with one-way data flow

import {useState} from 'react';

function SignUp(props){

const [emailAddress,setEmailAddress] = useState('');

const handleChange = (e)=>{

setEmailAddress(e.target.value);

return(

<>

<form>

<label>Enter your email address:

<input value={emailAddress} onChange={handleChange} type="text" />

</label>

</form>

<p>Your email address: {emailAddress}</p>

</>

export default SignUp;

USING DIFFERENT FORM ELEMENTS

HTML input elements are the most commonly used types of interactive elements. By changing the
type attribute of the input element, you can create inputs for a large and growing number of data

types, including:

➤➤button

➤➤checkbox

➤➤color

➤➤date

➤➤datetime- local

➤➤email

➤➤file

➤➤hidden

➤➤image

➤➤month

➤➤number

➤➤password

➤➤radio

HAT REFS ARE

Nothing is perfect, and that includes React. There are rare, but unavoidable, times when one way data
flow and the declarative way of only modifying children via props break down. In these cases, which I’ll
demonstrate in more detail and with plenty of examples in this chapter, a React developer needs to be
able to imperatively get into a child component or a DOM node to make changes or access some
property directly. For these cases, React provides an “escape hatch” called refs.

A ref is reference to a child component that allows you to modify a child component or DOM node from
the parent component, rather than by using the standard method of modifying children only by passing
props into them.

HOW TO CREATE A REF IN A CLASS COMPONENT

In a class component, refs are created using React.createRef. Once you have a ref, you can assign it to a
child component by passing it as the value of the ref attribute. Listing 9-1 shows how to create a ref to a
textarea element from a component called TextReader.

LISTING 9- 1: Creating a ref in a class component


import React,{Component} from 'react';

class TextReader extends Component {

constructor(props) {

super(props);

this.textView = React.createRef();

render() {

return (

<textarea ref={this.textView} value={this.props.bookText} />

);

HOW TO CREATE A REF IN A FUNCTION COMPONENT

In a function component, you can use the useRef hook to create a ref, as shown in Listing 9-2.

LISTING 9- 2: Creating a ref with useRef()

import {useRef} from 'react';

function TextReader(props) {

const textView = useRef(null);

return (

<textarea ref={textView} value={props.bookText} />

);

export default TextReader;

Styling React
How to style React components, and React user interfaces in general, can be a polarizing topic.

There are many ways to handle style in React, and you’re likely to see several of them used side-

by- side on most React projects.

THE IMPORTANCE OF STYLES

Style in web applications determines how individual elements look, including typefaces, weight of text,
colors, backgrounds, width, and height, for example. It also determines how elements relate to each
other and to the HTML document or browser window—their borders, margins, alignment, and position.
Certain CSS styles create animations. Still others affect how elements behave and how they look when
they’re in different states, such as hovered over, clicked, focused, and so on.

Even if you don’t add any style at all to your user interface, it’s still affected by the browser’s default
styles, which are rarely ideal. Styles also determine how your user interface will look on different sized
devices, when printed, and even how it will sound when read by a text-to- speech reader.

With styles determining so much of what the end user’s experience with your application will be, it’s
essential for a developer or a development team to give more than a little thought to how style will be
managed and implemented in a user interface

IMPORTING CSS INTO THE HTML FILE

The most basic way to style a React user interface is by importing one or more CSS files into the

HTML file that loads React. This can be done as simply as by opening up index.html, which lives

in the public folder in a Create React App project, and adding an HTML link element between the

<head> and </head> tags, as shown in Listing 10-1.

LISTING 10- 1: Adding an HTML link to the HTML file

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />

<meta name="viewport" content="width=device- width, initial-scale=1" />

<meta name="theme-color" content="#000000" />

<meta
name="description"

content="Web site created using create-react-app" />

<link rel="stylesheet" href="%PUBLIC_URL%/css/style.css" />

<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

</head>

<body>

<noscript>You need to enable JavaScript to run this app.</noscript>

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

</body>

</html>

In Create React App projects, the index.html file is a template, which gets compiled when you run npm
start or npm run build. Variables in the template are surrounded by the % character. So, in the CSS link
added in Listing 10-1, the %PUBLIC_URL% variable will be replaced with the actual URL where the
application is being served.

To use this method of styling React, just put a CSS file in the right place inside the public directory or
point the link to an external URL (such as a hosted stylesheet or a stylesheet library like Bootstrap).

Introducing Hooks

React Hooks give function components access to much of the functionality of React that was previously
only available with class components. Hooks also give developers a simpler syntax for using state,
performing tasks in response to lifecycle events, and reusing code.

WHAT ARE HOOKS?

Hooks are functions that are part of the React library which give you access to features of React that
were previously only available by extending the React.Component class. These features include state
and lifecycle, as well as refs and caching of function results (aka memoization). Hooks “hook into” React
from functions.

WHY WERE HOOKS INTRODUCED?

Hooks were introduced to solve several problems with the React library. The first is that React didn’t
have a simple way to share reusable functionality between components. Prior to React Hooks, solutions
such as higher- order components and render props (both of which are covered in Chapter 12) were
commonly used (and still are) for sharing functionality. However, higher-order components tend to
result in code and component trees that are difficult to read and overly complex. Code that renders
multiple levels of components within components withi.
Introducing Hooks

React Hooks give function components access to much of the functionality of React that was previously
only available with class components. Hooks also give developers a simpler syntax for using state,
performing tasks in response to lifecycle events, and reusing code.

WHAT ARE HOOKS?

Hooks are functions that are part of the React library which give you access to features of React that
were previously only available by extending the React.Component class. These features include state
and lifecycle, as well as refs and caching of function results (aka memoization). Hooks “hook into” React
from functions.

WHY WERE HOOKS INTRODUCED?

Hooks were introduced to solve several problems with the React library. The first is that React didn’t
have a simple way to share reusable functionality between components. Prior to React Hooks, solutions
such as higher- order components and render props (both of which are covered in Chapter 12) were
commonly used (and still are) for sharing functionality. However, higher-order components tend to
result in code and component trees that are difficult to read and overly complex. Code that renders
multiple levels of components within components withi.

RULES OF HOOKS

Although different hooks accomplish different things, all of them have two important rules which

must be followed:

1. Hooks can only be used in function components.

2. Hooks must be called at the top level of your function components—meaning inside the

function, but not inside of a statement or inner function. Because hooks need to run just once

every time your function component runs, they can’t be called from inside of conditional

statements, loops, or nested functions.

THE BUILT-IN HOOKS

React has 10 built-in hooks that you can use without needing to install anything else. These built-in

hooks are:

➤➤useState

➤➤useEffect
➤➤useContext

➤➤useReducer

➤➤useCallback

➤➤useMemo

➤➤useRef

➤➤useImperativeHandle

➤➤useLayoutEffect

➤➤useDebugValue

The first three hooks—use.

LISTING 11- 1: A number guessing game with useState

import {useState} from 'react';

function NumberGuessing(props){

const [score,setScore] = useState(0);

const [guess,setGuess] = useState('');

const checkNumber =()=>{

const randomNumber = Math.floor(Math.random() * 10)+1;

if (Number(guess) === randomNumber){

IMPORTING ALL THE HOOKS

In reality, since hooks are part of the React library, you can import all of the hooks

at once by importing the entire React library and then referencing them using dot

notation, like this:

import React from 'react';

const [state,setState] = React.useState();


Although there’s no real problem with using hooks this way, it’s more common, and perhaps more
efficient, to import just the hooks you need individually using named imports. If your component makes
use of multiple hooks, separate them with commas inside of the curly braces, like this:

import {useState,useEffect,useCallback} from 'react';

The Built-in Hooks ❘ 261

setScore(()=>score+1);

return (

<>

What number (between 1 and 10) am I thinking of?

<input value={guess}

type="number"

min="1"

max="10"

onChange={(e)=>setGuess(e.target.value)}

/>

<button onClick={checkNumber}>Guess!</button>

<p>Your score: {score}</p>

</>

export default NumberGuessing;


Custom Hooks in React: Writing, Using, and Debugging with useDebugValue
1. Introduction to Custom Hooks

React Hooks were introduced in React 16.8 to allow developers to use state and other React
features without writing class components. Custom Hooks are user-defined functions that start
with 'use' and allow developers to extract and reuse stateful logic across multiple components.

Rules of Hooks:
1. Only call hooks at the top level.
2. Only call hooks from React functions (functional components or custom hooks).

2. Writing Custom Hooks

A custom hook is simply a JavaScript function whose name starts with 'use' and that may call
other hooks. Custom hooks allow us to reuse stateful logic without duplicating code.

Example: useCounter Hook

This hook manages a counter state and exposes increment and decrement methods:

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

const increment = () => setCount(count + 1);


const decrement = () => setCount(count - 1);

return { count, increment, decrement };


}

This hook can be reused across multiple components without rewriting the counter logic.

3. Finding and Using Custom Hooks

Custom hooks can be written inside your project and stored in a 'hooks' folder for better
organization. They can also be shared via npm or sourced from community-driven libraries such
as usehooks.com.

To use a custom hook, simply import it and call it like any other React hook:

import useCounter from './hooks/useCounter';


function CounterComponent() {
const { count, increment, decrement } = useCounter(10);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}

4. Labeling Custom Hooks with useDebugValue

React provides the useDebugValue hook to help developers label and debug custom hooks inside
React DevTools. This is especially useful when building reusable hooks shared across projects.

Example: useAuth Custom Hook with useDebugValue:


function useAuth(user) {
const [isLoggedIn, setIsLoggedIn] = useState(!!user);
useDebugValue(isLoggedIn ? 'User Logged In' : 'User Logged Out');
return isLoggedIn;
}

In React DevTools, this hook will show either 'User Logged In' or 'User Logged Out' making
debugging much easier.

5. Summary & Best Practices

1. Always prefix custom hooks with 'use'.


2. Use custom hooks to extract reusable logic.
3. Place hooks inside a dedicated folder like '/hooks' for maintainability.
4. Use useDebugValue for improved debugging in DevTools.
5. Avoid writing overly complex hooks; keep them modular.

Diagrams (for visualization):

• Flow of reusing useCounter hook across multiple components.


• Component hierarchy diagram with shared custom hook.
• React DevTools screenshot showing useDebugValue output.

You might also like