FSD Unit2 Notes
FSD Unit2 Notes
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:
⮚ 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
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();">
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
Example:
var x = 10; // var variable
let y = 20; // let variable
const z = 30; // constant variable
2. JavaScript Strings
Creating strings:
let str1 = "Hello";
- toLowerCase() → str.toLowerCase()
- trim() → str.trim()
Example:
JAVASCRIPT"
3. JavaScript Arrays
Creating arrays:
let arr1 = [1, 2, 3, 4];
let arr2 = new Array("Apple", "Banana", "Cherry");
Accessing elements:
console.log(arr1[0]); // 1
- pop() → arr.pop()
- shift() → arr.shift()
- unshift(item) → arr.unshift("Lemon")
- indexOf(item) → arr.indexOf("Banana")
- join(",") → arr.join(", ")
Example:
Conditions allow decision-making in JavaScript programs. They help execute certain blocks of
code based on logical tests.
1. if Statement:
if (condition) {
// code runs if condition is true
}
2. if...else Statement:
if (condition) {
// code if true
} else {
// code if false
}
4. switch Statement:
switch(expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}
2. Loops
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);
3. Responding to Events
Events are actions that happen in the browser (like clicks, keypress, mouse movements).
JavaScript can respond to these events.
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:
JavaScript libraries and frameworks provide pre-written code to speed up development, add
functionality, and improve maintainability.
Example (jQuery):
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
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
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
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.
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.
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.
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.
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.
Before we talk about components, it’s important to understand the relationship between components
and elements in React.
Components Define Elements
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‑
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.
Accessing Props
shows the Farm component and how it makes use of the data passed into it.
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
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:
You potentially save a few keystrokes inside your component by using a named import to import the
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):
If you import Component using a named import, the header of your new component will look
like this:
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.
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.
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();
this.setState({
todolist:list
})
handleChange(e){
this.setState({item:e.target.value});
render(){
(todo,index)=><p key={index}>{todo}</p>);
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
id="todoitem"
value={this.state.item}
onChange={this.handleChange}
<button type="submit">
Add
</button>
{currentTodos}
</form>
);
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.
function ToDoFunction(props){
e.preventDefault();
setTodoList(list)
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>
);
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
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
➤➤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
➤➤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,
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
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
To put it simply, listening for events in a React component and handling events is done similarly
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
<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.
<head>
<script>
function validate(e){
</script>
</head>
<body>
<form id="signup-form">
<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:
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.
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.
function EventProps(){
const logClick=(e)=>{
console.dir(e);
return(
}
export default EventProps;
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.
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.
function WarningButton(){
return (
);
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:
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, :
function SignUp(props){
return(
<form>
</form>
Listing 8-3 shows a controlled text input that updates using one- way data flow in a function
component.
function SignUp(props){
setEmailAddress(e.target.value);
return(
<>
<form>
</label>
</form>
</>
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
➤➤file
➤➤hidden
➤➤image
➤➤month
➤➤number
➤➤password
➤➤radio
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.
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.
constructor(props) {
super(props);
this.textView = React.createRef();
render() {
return (
);
In a function component, you can use the useRef hook to create a ref, as shown in Listing 9-2.
function TextReader(props) {
return (
);
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-
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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta
name="description"
</head>
<body>
<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.
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.
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.
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.
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:
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
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
function NumberGuessing(props){
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
setScore(()=>score+1);
return (
<>
<input value={guess}
type="number"
min="1"
max="10"
onChange={(e)=>setGuess(e.target.value)}
/>
<button onClick={checkNumber}>Guess!</button>
</>
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).
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.
This hook manages a counter state and exposes increment and decrement methods:
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
This hook can be reused across multiple components without rewriting the counter logic.
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:
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
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.
In React DevTools, this hook will show either 'User Logged In' or 'User Logged Out' making
debugging much easier.