You are on page 1of 35

** HTML

Father of html - Tim Berners-Lee

What is HTML?
HTML stands for Hyper Text Markup Language.
HTML is the standard markup language for creating Web pages.
HTML describes the structure of a Web page.

** The <!DOCTYPE html> declaration defines that this document is an HTML5 document.
The <!DOCTYPE> declaration represents the document type, and helps browsers to
display web pages correctly.

It must only appear once, at the top of the page (before any HTML tags).

The <!DOCTYPE> declaration is not case sensitive.

The <!DOCTYPE> declaration for HTML5 is:

** The <html> element is the root element of an HTML page.


The <head> element contains meta information about the HTML page.
The <title> element specifies a title for the HTML page (which is shown in the
browser's title bar or in the page's tab).
The <body> element defines the document's body, and is a container for all the
visible contents, such as headings, paragraphs, images, hyperlinks, tables,
lists, etc.
The <h1> element defines a large heading.
The <p> element defines a paragraph.

** HTML Element?
an HTML element is defined by a start tag, some content, and an end tag:
<h1>My First Heading</h1>

** HTML Headings +
HTML headings are defined with the <h1> to <h6> tags.

** Empty HTML Elements


HTML elements with no content are called empty elements.
1. The <br> tag defines a line break.
2. The <hr> tag defines a thematic break in an HTML page.The <hr> tag is an
empty tag, which means that it has no end tag.
3. The text inside a <pre> element, and it preserves both spaces and line
breaks.

** HTML Attributes
All HTML elements can have attributes.
Attributes provide additional information about elements.
Attributes are always specified in the start tag.
Attributes usually come in name/value pairs like: name="value".

** HTML Formatting Elements


<b> - Bold text
<strong> - Important text
<i> - Italic text
<em> - Emphasized text
<mark> - Marked text
<small> - Smaller text
<del> - Deleted text
<ins> - Inserted text
<sub> - Subscript text
<sup> - Superscript text

** Semantic Elements in HTML


<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>

** HTML Links
<a href="https://www.w3schools.com">This is a link</a>
The link's destination is specified in the href attribute.

1. HTML Links - Hyperlinks


<a href="url">link text</a>
The most important attribute of the <a> element is the href attribute, which
indicates the link's destination.

2. HTML Links - The target Attribute


The target attribute specifies where to open the linked document.

_self - Default. Opens the document in the same window/tab as it was clicked.
_blank - Opens the document in a new window or tab.
_parent - Opens the document in the parent frame.
_top - Opens the document in the full body of the window.

3. HTML Links - Use an Image as a Link


<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;">
</a>

4. Link to an Email Address


<a href="mailto:someone@example.com">Send email</a>

5. Button as a Link
<button onclick="document.location='default.asp'">HTML Tutorial</button>

6. The HTML <link> Element ** MOST IMPORTANT **


<link rel="stylesheet" href="mystyle.css">

** Create a Bookmark in HTML


1. First, use the id attribute to create a bookmark:

<h2 id="C4">Chapter 4</h2>

2. Then, add a link to the bookmark ("Jump to Chapter 4"), from within the same
page:

Example
<a href="#C4">Jump to Chapter 4</a>

3. You can also add a link to a bookmark on another page:

<a href="html_demo.html#C4">Jump to Chapter 4</a>

[Note] * Use the id attribute (id="value") to define bookmarks in a page


* Use the href attribute (href="#value") to link to the bookmark

** HTML Images
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
The source file (src), alternative text (alt), width, and height are provided
as attributes:

1. Image Floating
<p><img src="smiley.gif" alt="Smiley face"
style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>

<p><img src="smiley.gif" alt="Smiley face"


style="float:left;width:42px;height:42px;">
The image will float to the left of the text.</p>

Common Image Formats


Abbreviation File Format File Extension
APNG Animated Portable Network Graphics .apng
GIF Graphics Interchange Format .gif
ICO Microsoft Icon .ico, .cur
JPEG Joint Photographic Expert Group image
.jpg, .jpeg, .jfif, .pjpeg, .pjp
PNG Portable Network Graphics .png
SVG Scalable Vector Graphics .svg

2. HTML <map> Tag


The <map> tag is used to define an image map. An image map is an image with
clickable areas.
The required name attribute of the <map> element is associated with the
<img>'s usemap attribute and creates a relationship between the image and the map.
The <map> element contains a number of <area> elements, that defines the
clickable areas in the image map.

Example:
<img src="planets.gif" width="145" height="126" alt="Planets"
usemap="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

3. HTML <picture> Tag ----- Defines a container for multiple image


resources
<picture>
<source media="(min-width:650px)" srcset="img_pink_flowers.jpg">
<source media="(min-width:465px)" srcset="img_white_flower.jpg">
<img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
** Background Image on a HTML element
<p style="background-image: url('img_girl.jpg');">

** HTML Tables
Define an HTML Table ---- A table in HTML consists of table cells inside rows
and columns.
Table Cells ----- Each table cell is defined by a <td> and a </td> tag.

Example:
<table>
<tr> table row
<th>Person 1</th> table heading
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td> table data
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

1. Rowspan ---- To make a cell span over multiple rows, use the rowspan
attribute.
Colspan ---- To make a cell span over multiple columns, use the colspan
attribute.

2.The <colgroup> element is used to style specific columns of a table.

HTML Table Colgroup


If you want to style the two first columns of a table, use the <colgroup> and
<col> elements.
There is only a very limited selection of CSS properties that are allowed to
be used in the colgroup:
width property
visibility property
background properties
border properties

Note: The <colgroup> tag must be a child of a <table> element and should be placed
before any other table elements, like <thead>, <tr>, <td> etc., but after the
<caption> element, if present.

Examples:
<table>
<colgroup>
<col span="2">
<col span="3" style="visibility: collapse">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
</tr>
</table>

** HTML Lists
1. Unordered HTML List
2. Ordered HTML List
3. HTML Description Lists.

1. Unordered HTML List


An unordered list starts with the <ul> tag. Each list item starts with the <li>
tag.
The list items will be marked with bullets (small black circles) by default:
Unordered HTML List - Choose List Item Marker - The CSS [list-style-type]
property is used to define the style of the list item marker.
disc , circle , square , none .
Example :
<ul style="list-style-type:disc;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
2. Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li>
tag.
The list items will be marked with numbers by default:
Ordered HTML List - The [type] attribute of the <ol> tag, defines the type of
the list item marker:
type="1" - numbers (default)
type="A" - uppercase letters , type="a" - lowercase letters
type="I" - uppercase roman numbers , type="i" - lowercase roman numbers.
Example :
<ol type="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
3. HTML Description Lists
A description list is a list of terms, with a description of each term.
The <dl> tag defines the description list, the <dt> tag defines the term
(name), and the <dd> tag describes each term:
Example:
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

** Block-level Elements
A block-level element always starts on a new line,& the browsers automatically
add some space (a margin) before and after the content.
A block-level element always takes up the full width available.
Two commonly used block elements are: <p> and <div>.

1. Here are the block-level elements in HTML:


<address> <article> <aside> <blockquote> <canvas> <dd> <div> <dl> <dt>
<fieldset> <figcaption> <figure> <footer> <form><h1>-<h6> <header> <hr> <li>
<main> <nav> <noscript> <ol> <p> <pre> <section> <table> <tfoot> <ul>
<video>.

** Inline Elements
An inline element does not start on a new line .
An inline element only takes up as much width as necessary.

1. Here are the inline elements in HTML:


<a> <abbr> <acronym> <b> <big> <br> <button> <cite> <code> <em> <i>
<img> <input> <label> <map> <q> <script> <select> <small> <span> <strong>
<sub> <sup> <textarea> <time> <tt> <var>.

** The <div> Element


The <div> element is often used as a container for other HTML elements.
The <div> element has no required attributes, but style, class and id are
common.
When used together with CSS, the <div> element can be used to style blocks of
content:

Example:
<div style="background-color:black;color:white;padding:20px;">
<h2>London</h2>
<p>London is the capital city of England. It is the most populous city in
the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
</div>

** The <span> Element


The <span> element is an inline container used to mark up a part of a text,
or a part of a document.
The <span> element has no required attributes, but style, class and id are
common.
When used together with CSS, the <span> element can be used to style parts of
the text:

Example:
<p>My mother has <span style="color:blue;font-weight:bold;">blue</span> eyes
and my father has <span style="color:darkolivegreen;font-weight:bold;">dark
green</span> eyes.</p>

** HTML Iframes
An HTML iframe is used to display a web page within a web page.
Syntax:
<iframe src="url" title="description"></iframe>

It is a good practice to always include a [title] attribute for the <iframe>.


This is used by screen readers to read out what the content of the iframe is.
Use the [height] and [width] attributes to specify the size of the
iframe.bydefault it is specified by pixels.
Or you can add the [style] attribute and use the CSS height and width
properties:

** The HTML <meta> Element


1. Define the character set used:
<meta charset="UTF-8">

2. Define keywords for search engines:


<meta name="keywords" content="HTML, CSS, JavaScript">

3. Define a description of your web page:


<meta name="description" content="Free Web tutorials">
4. Define the author of a page:
<meta name="author" content="John Doe">

5. Refresh document every 30 seconds:


<meta http-equiv="refresh" content="30">

6. Setting the viewport to make your website look good on all devices:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

** HTML Responsive Web Design


Responsive web design is about creating web pages that look good on all
devices!
A responsive web design will automatically adjust for different screen sizes
and viewports.

** HTML Forms
An HTML form is used to collect user input. The user input is most often sent
to a server for processing.
1. The <form> Element
The HTML <form> element is used to create an HTML form for user input:
2. The <input> Element
The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the type
attribute.

The form-data can be sent as URL variables (with method="get") or as HTTP post
transaction (with method="post").

** The HTML <form> Elements


The HTML <form> element can contain one or more of the following form elements:
<input>
<label>
<select>
<textarea>
<button>
<fieldset>
<legend>
<datalist>
<output>
<option>
<optgroup>

** HTML Input Types


Here are the different input types you can use in HTML:
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="reset">
<input type="search">
<input type="submit">
<input type="tel">
<input type="text">
<input type="time">
<input type="url">
<input type="week">

** HTML Input Attributes


value , readonly , disabled , size , maxlength , min and max , multiple ,
pattern , placeholder , required , autofocus , height and width .

** HTML Canvas Graphics


The HTML <canvas> element is used to draw graphics on a web page.
The <canvas> element is only a container for graphics. You must use JavaScript
to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding
images.
Example:
<canvas id="myCanvas" width="200" height="100"></canvas>

** HTML SVG Graphics


SVG defines vector-based graphics in XML format.
The HTML <svg> Element
The HTML <svg> element is a container for SVG graphics.
SVG has several methods for drawing paths, boxes, circles, text, and graphic
images.
Example:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4"
fill="yellow" />
</svg>

Canvas
SVG
Resolution dependent.
Resolution independent
No support for event handlers.
Support for event handlers
Poor text rendering capabilities.
Best suited for applications with large rendering

areas (Google Maps).


You can save the resulting image as .png or .jpg
Slow rendering if complex (anything that uses the DOM

a lot will be slow).


Well suited for graphic-intensive games.
Not suited for game applications.

** The HTML <video> Element


Example
<video width="320" height="240" controls> The controls attribute adds
video controls, like play, pause, and volume.
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

** The HTML <audio> Element


Example
<audio controls> The controls attribute adds
audio controls, like play, pause, and volume.
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

** HTML YouTube Videos


Example
<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY">
</iframe>

CASCADING STYLE SHEET - CSS

Father of css - Hakon Wium Lie

** What is CSS
CSS stands for Cascading Style Sheet. It is a popular styling language which is
used with HTML to design websites.
SGML (Standard Generalized Markup Language) is the origin of CSS.

** There are three methods to [integrate/way to insert] CSS on web pages.


1. Inline method - It is used to insert style sheets in HTML document
2. Embedded/Internal method - It is used to add a unique style to a single
document
3. Linked/Imported/External method - It is used when you want to make changes on
multiple pages.

** The CSS [opacity] property is used to specify the transparency of an element. In


simple word, you can say that it specifies the clarity of the image. In technical
terms, Opacity is defined as the degree to which light is allowed to travel through
an object.

** [RWD] stands for Responsive Web Design. This technique is used to display the
designed page perfectly on every screen size and device, for example, mobile,
tablet, desktop and laptop. You don't need to create a different page for each
device.

** The CSS [float] property is used to move the image to the right or left along
with the texts to be wrapped around it. It doesn't change the property of the
elements used before it.

** The [z-index] helps to specify the stack order of positioned elements that may
overlap one another. The z-index default value is zero and can take on either a
positive or negative number.
An element with a higher z-index is always stacked above than a lower index.

** [visibility]: hidden hides the element, but it occupies space and affects the
layout of the document.
[display]: none also hides the element but not occupy space. It will not affect
the layout of the document.

** A [universal selector] is a selector that matches any element type's name


instead of selecting elements of a particular type.

** [Class] is a way of using HTML elements for styling. They are not unique and
have multiple elements.
Whereas [ID] is unique and it can be assigned to a single element.

** 1. [Block] Elements are <div> and <p>. They usually start on a new line and can
take space for an entire row or width.
2. [Inline] elements are <a>, <span>, <strong>, and <img> tags. They don't start
on a new line. However, they appear on the same line as the content and tags beside
them.
3. [Inline - block] elements have padding and margins and set height and width
values. Though, they are similar to inline elements.

** The main difference is that [relative] is used for the same tag in CSS. If we
write right:20 px, then padding shifts 20 px in the right. Whereas [absolute] is
relative to the non-static parent, i.e., if we write right:20 px, the result will
be 20 px far from the right edge of the parent element.

** CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

1. Simple selectors (select elements based on name, id, class)


2. Combinator selectors (select elements based on a specific relationship between
them)
3. Pseudo-class selectors (select elements based on a certain state)
4. Pseudo-elements selectors (select and style a part of an element)
5. Attribute selectors (select elements based on an attribute or attribute value).

** CSS Comments --- starts with /* and ends with */ HTML comments ---- <!--...-->

** CSS COLORS:
1. RGB Colors - An RGB color value represents RED, GREEN, and BLUE light
sources.
defines the intensity of the color between 0 and 255.
2. HEX Colors - A hexadecimal color is specified with: #RRGGBB, where the RR
(red), GG (green) and BB (blue) hexadecimal integers specify the components of the
color.
hexadecimal values between 00 and ff (same as decimal 0-255).
3. HSL Colors - HSL stands for hue, saturation, and lightness.
hsl(hue, saturation, lightness)
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120
is green, and 240 is blue.
Saturation is a percentage value. 0% means a shade of gray, and
100% is the full color.
Lightness is also a percentage. 0% is black, 50% is neither
light or dark, 100% is white

** CSS Backgrounds
1. background-color - background-color: lightblue; specifies the
background color
2. background-image - background-image: url("paper.gif");
3. background-repeat - background-repeat: no-repeat; Showing the
background image only once
4. background-attachment - background-attachment: fixed; whether the
background image should scroll or be fixed
5. background-position - background-position: right top; used to
specify the position of the background image.
6. background (shorthand property) - background: #ffffff url("img_tree.png")
no-repeat right top;

** Opacity / Transparency
The opacity property specifies the opacity/transparency of an element. It can
take a value from 0.0 - 1.0. The lower value, the more transparent:

** CSS Border Style


dotted - Defines a dotted border
dashed - Defines a dashed border
solid - Defines a solid border
double - Defines a double border
groove - Defines a 3D grooved border. The effect depends on the border-color
value
ridge - Defines a 3D ridged border. The effect depends on the border-color value
inset - Defines a 3D inset border. The effect depends on the border-color value
outset - Defines a 3D outset border. The effect depends on the border-color value
none - Defines no border
hidden - Defines a hidden border

** CSS Border Width


The width can be set as a specific size (in px, pt, cm, em, etc) or by using one
of the three pre-defined values: thin, medium, or thick:
1. border-width: 5px 20px; /* 5px top and bottom, 20px on the sides */
2. border-width: 25px 10px 4px 35px; /* 25px top, 10px right, 4px bottom and
35px left */

** CSS Border Color - border-color: red;


** CSS Border sides - Individual Sides(top, right, bottom, and left): border-
style: dotted /solid;
** CSS Shorthand Border Property - combination of this three(border-width,border-
style (required),border-color).
border: 5px solid red;

** CSS Margins
The CSS margin properties are used to create space around elements, outside of
any defined borders.
margin-top margin-top: 100px;
margin-right
margin-bottom
margin-left margin-left: inherit;
All the margin properties can have the following values: auto,length( in px, pt,
cm, etc.), % ,inherit.
* shorthand margin: 25px 50px 75px 100px;

** CSS Padding
The CSS padding properties are used to generate space around an element's
content, inside of any defined borders.
padding-top
padding-right
padding-bottom
padding-left

Padding - Shorthand Property ex: padding: 25px 50px 75px 100px;


** CSS Box Model
In CSS, the term "box model" is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It
consists of: margins, borders, padding, and the actual content. The image below
illustrates the box model
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent

Example :
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}

** CSS Text

1. Text Color - color property is used to set the color of the text. example:
color: blue;

2. CSS Text Alignment


* text-align
text-align property is used to set the horizontal alignment of a text.
A text can be left or right aligned, centered, or justified.
Example: text-align: right;

* text-align-last
text-align-last property specifies how to align the last line of a text.
Example: text-align-last: right;

* direction
* unicode-bidi
The direction and unicode-bidi properties can be used to change the text
direction of an element:
Example: direction: rtl;
unicode-bidi: bidi-override;

* vertical-align
The vertical-align property sets the vertical alignment of an element.
Example: vertical-align: baseline/ text-top/ text-bottom/sub/super;

3. CSS Text Decoration


* text-decoration-line
Example: text-decoration-line: overline/ line-through/ underline/ overline
underline;

* text-decoration-color
Example: text-decoration-color: red;

* text-decoration-style
Example: text-decoration-style: solid/ double/ dotted/ dashed/ wavy;

* text-decoration-thickness
Example: text-decoration-thickness: auto/ 5px/ 25%;

* text-decoration
The text-decoration property is a shorthand property for of the above:
Example: text-decoration: underline red double 5px;

4. CSS Text Transformation


text-transform property is used to specify uppercase and lowercase letters
in a text.
Example: text-transform: uppercase/ lowercase/ capitalize;

5. CSS Text Spacing


* text-indent
text-indent property is used to specify the indentation of the first line
of a text:
Example: text-indent: 50px;

* letter-spacing
The letter-spacing property is used to specify the space between the
characters in a text.
Example: letter-spacing: 5px;

* line-height
The line-height property is used to specify the space between lines:
Example: line-height: 0.8;

* word-spacing
The word-spacing property is used to specify the space between the words
in a text.
Example: word-spacing: 10px;

* white-space
The white-space property specifies how white-space inside an element is
handled.
Example: white-space: nowrap;

6. CSS Text Shadow


In its simplest use, you only specify the horizontal shadow (2px) and the
vertical shadow (2px):
Example: text-shadow: 2px 2px;
text-shadow: 2px 2px red;
text-shadow: 0 0 3px #ff0000, 0 0 5px #0000ff;

** CSS Fonts
1. CSS font-family Property - font-family: "Times New Roman", Times,
serif;

2. CSS Font Style


The font-style property is mostly used to specify italic text.
Example: font-style: normal/ italic/ oblique;

* Font Weight - font-weight property specifies the weight of a font:


font-weight: normal/ bold;

* Font Variant - specifies whether or not a text should be displayed in a


small-caps font.
font-variant: normal/ small-caps;

3. CSS Font Size - The font-size property sets the size of the text.
font-size: 40px/ 2.5em; /* 40px/16=2.5em */;

4. The CSS Font Property


The font property is a shorthand property for:font-style,font-variant,font-
weight,font-size/line-height,font-family.
font: italic small-caps bold 12px/30px Georgia, serif;

** CSS Links
Links can be styled with any CSS property (e.g. color, font-family,
background, etc.).
The four links states are:
1. a:link - a normal, unvisited link
2. a:visited - a link the user has visited
3. a:hover - a link when the user mouses over it
4. a:active - a link the moment it is clicked.
Example:
a:link {
color: red;
}

** CSS Layout - The display Property


1. Block-level Elements
A block-level element always starts on a new line and takes up the full
width available (stretches out to the left and right as far as it can).<div>

2. Inline Elements
An inline element does not start on a new line and only takes up as much
width as necessary.
This is an inline <span> element inside a paragraph.

** CSS Layout - The position Property


The position property specifies the type of positioning method used for an
element (static, relative, fixed, absolute or sticky).
Elements are then positioned using the top, bottom, left, and right
properties. However, these properties will not work unless the position property is
set first. They also work differently depending on the position value.

1. position: static;
HTML elements are positioned static by default.
Static positioned elements are not affected by the top, bottom, left, and right
properties.
An element with position: static; is not positioned in any special way; it is
always positioned according to the normal flow of the page:

2. position: relative;
An element with position: relative; is positioned relative to its normal
position.
Setting the top, right, bottom, and left properties of a relatively-positioned
element will cause it to be adjusted away from its normal position. Other content
will not be adjusted to fit into any gap left by the element.

3. position: fixed;
An element with position: fixed; is positioned relative to the viewport, which
means it always stays in the same place even if the page is scrolled. The top,
right, bottom, and left properties are used to position the element.
A fixed element does not leave a gap in the page where it would normally have
been located.

4. position: absolute;
An element with position: absolute; is positioned relative to the nearest
positioned ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it
uses the document body, and moves along with page scrolling.
Note: Absolute positioned elements are removed from the normal flow, and can
overlap elements.

5. position: sticky;
An element with position: sticky; is positioned based on the user's scroll
position.
A sticky element toggles between relative and fixed, depending on the scroll
position. It is positioned relative until a given offset position is met in the
viewport - then it "sticks" in place (like position:fixed).

** CSS Layout - Overflow


The CSS overflow property controls what happens to content that is too big to
fit into an area.
overflow property specifies whether to clip the content or to add scrollbars.
overflow property are:
* visible - Default. The overflow is not clipped. The content renders outside
the element's box
* hidden - The overflow is clipped, and the rest of the content will be
invisible
* scroll - The overflow is clipped, and a scrollbar is added to see the rest
of the content
* auto - Similar to scroll, but it adds scrollbars only when necessary
Example: overflow: visible;

** CSS Specificity
If there are two or more CSS rules that point to the same element, the
selector with the highest specificity value will "win", and its style declaration
will be applied to that HTML element.

** CSS Units
CSS has several different units for expressing a length.
Many CSS properties take "length" values, such as width, margin, padding,
font-size, etc.
Length is a number followed by a length unit, such as 10px, 2em, etc.

* There are two types of length units: absolute and relative.

* Absolute Lengths
The absolute length units are fixed and a length expressed in any of these
will appear as exactly that size.cm,mm,px,pc and etc.
Absolute length units [are not recommended for use on screen, because screen
sizes vary so much].
However, they can be used if the output medium is known, such as for
[print layout].

* Relative Lengths
Relative length units specify a length relative to another length property.
Relative length units scale better between different rendering mediums.
em,vh,vw,%,rem and etc.

** CSS The !important Rule


In fact, if you use the !important rule, it will override ALL previous
styling rules for that specific property on that element!

** CSS Flexbox - The Flexible Box Layout Module, makes it easier to design
flexible responsive layout structure without using float or positioning.
Before the Flexbox Layout module, there were four layout modes:
1. Block, for sections in a webpage
2. Inline, for text
3. Table, for two-dimensional table data
4. Positioned, for explicit position of an element

* Parent Element (Container)


* flex-direction - defines in which direction the container wants to stack
the flex items.
display: flex;
flex-direction: column/ column-reverse/ row/ row-
reverse;

* flex-wrap - specifies whether the flex items should wrap or not.


flex-wrap: wrap[it will be folded]/ nowrap/ wrap-
reverse;

* flex-flow - is a shorthand property for setting both the flex-


direction and flex-wrap properties. ex: flex-flow: row wrap;

* justify-content - The justify-content property is used to align the flex


items:
justify-content: center/ flex-start/ flex-end/
space-around/ space-between;

* align-items - The align-items property is used to align the flex


items.in Y-axis
align-items: center/ flex-start/ flex-end/ stretch/
baseline;

* align-content - The align-content property is used to align the flex


lines.
align-content: space-between/ space-around/
stretch/ center/ flex-start/ flex-end;

* Child Elements (Items)

* order - specifies the order of the flex items., default value is 0.


Example:
<div class="flex-container">
<div style="order: 3">1</div>
<div style="order: 2">2</div>
<div style="order: 4">3</div>
<div style="order: 1">4</div>
</div>

* flex-grow - specifies how much a flex item will grow relative to the
rest of the flex items., default value is 0.
Example:
<div class="flex-container">
<div style="flex-grow: 1">1</div>
<div style="flex-grow: 1">2</div>
<div style="flex-grow: 8">3</div>
</div>

* flex-shrink - specifies how much a flex item will shrink relative to the
rest of the flex items.
Example: <div style="flex-shrink: 0">3</div>

* flex-basis - specifies the initial length of a flex item.


Example: <div style="flex-basis: 200px">3</div>
* flex - The flex property is a shorthand property for the flex-grow,
flex-shrink, and flex-basis properties.
Example: <div style="flex: 0 0 200px">3</div>

* align-self - The align-self property specifies the alignment for the


selected item inside the flexible container.
Example: <div style="align-self: center">3</div>

** CSS Grid Layout Module


The CSS Grid Layout Module offers a grid-based layout system, with rows and
columns, making it easier to design web pages without having to use floats and
positioning.
An HTML element becomes a grid container when its display property is set to
grid or inline-grid.

* Grid Gaps - column-gap: 50px; row-gap: 50px; gap: 50px 100px;


* Grid Lines - The lines between columns are called column lines.
Example:
Place a grid item at column line 1, and let it end on column line 3:
.item1 {
grid-column-start: 1;
grid-column-end: 3;
}

* The grid-template-columns Property


defines the number of columns in your grid layout, and it can define the width
of each column.
Example: grid-template-columns: auto auto auto auto;

* The justify-content Property


The justify-content property is used to align the whole grid inside the
container.
Example: justify-content: space-evenly/ space-around/ space-between/ center/
start/ end;

* The align-content Property


The align-content property is used to vertically align the whole grid inside
the container.
Example: align-content: center/ space-evenly/ space-around/ space-around/
start/ end;

* Child Elements (Items) - A grid container contains grid items.


1. The grid-column Property:
property defines on which column(s) to place an item.You define where the
item will start, and where the item will end.
Example: grid-column: 1 / 5;

* The grid-row Property: grid-row: 1 / 4; grid-row: 1 / span 2;

* The grid-area Property


The grid-area property can be used as a shorthand property for the grid-row-
start, grid-column-start, grid-row-end and the grid-column-end properties.
Example: grid-area: 1 / 2 / 5 / 6;

** CSS Transitions
CSS transitions allows you to change property values smoothly, over a given
duration.
* transition - A shorthand property for setting the four transition
properties into a single property.
transition: width 2s linear 1s; Pro,Dur,timi,del

* transition-duration - Specifies how many seconds or milliseconds a


transition effect takes to complete
Example: transition-duration: 2s;

* transition-delay - specifies a delay (in seconds) for the transition


effect. transition-delay: 1s;

* transition-property - Specifies the name of the CSS property the


transition effect is for. transition-property: width;

* transition-timing-function - specifies the speed curve of the transition


effect.
transition-timing-function: ease-in-out/ease/linear/ease-in/ease-
out/cubic-bezier(n,n,n,n);

** CSS Animations - CSS allows animation of HTML elements without using


JavaScript or Flash!
An animation lets an element gradually change from one style to another.
You can change as many CSS properties you want, as many times as you
want.
To use CSS animation, you must first specify some keyframes for the
animation.
Keyframes hold what styles the element will have at certain times.

1. @keyframes
When you specify CSS styles inside the @keyframes rule, the animation will
gradually change from the current style to the new style at certain times.
Example: @keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}

2. animation-name - animation-name: example;

3. animation-duration - defines how long an animation should take to complete.


animation-duration: 4s;

4. animation-delay - specifies a delay for the start of an animation.


animation-delay: 2s;

5. animation-iteration-count - specifies the number of times an animation


should run. animation-iteration-count: 3;

6. animation-direction - specifies whether an animation should be played


forwards, backwards or in alternate cycles.
normal - The animation is played as normal (forwards). This is default
reverse - The animation is played in reverse direction (backwards)
alternate - The animation is played forwards first, then backwards
alternate-reverse - The animation is played backwards first, then
forwards
Example: animation-direction: reverse;

7. animation-timing-function - specifies the speed curve of the animation.


ease - Specifies an animation with a slow start, then fast, then
end slowly (this is default)
animation-timing-function:linear / ease-in / ease-out / ease-in-out /
cubic-bezier(n,n,n,n);

8. animation-fill-mode - specifies a style for the target element when the


animation is not playing (before it starts, after it ends, or both).
Example: animation-fill-mode: forwards/ none/ backwards/ both;

9. animation - A shorthand property for setting all the animation properties


Example: animation: example 5s linear 2s infinite alternate;

10. animation-play-state Specifies whether the animation is running or paused

** CSS Media Queries


Media queries in CSS3 extended the CSS2 media types idea: Instead of looking
for a type of device, they look at the capability of the device.
Media queries can be used to check many things, such as:
width and height of the viewport
width and height of the device
orientation (is the tablet/phone in landscape or portrait mode?)
resolution

* Media Query Syntax


@media not|only mediatype and (expressions) {
CSS-Code;
}

* CSS3 Media Types


Value Description
all Used for all media type devices
print Used for printers
screen Used for computer screens, tablets, smart-phones
etc.
speech Used for screenreaders that "reads" the page out
loud.

* Example
@media screen and (min-width: 480px) {
#leftsidebar {width: 200px; float: left;}
#main {margin-left: 216px;}
}

** CSS box-sizing Property


The box-sizing property in CSS defines how the user should calculate the total
width and height of an element i.e padding and borders, are to be included or not.
Syntax:
box-sizing: content-box|border-box;

* content-box: This is the default value of the box-sizing property. In this


mode, the width and height properties include only the content. Border and padding
are not included in it i.e if we set an element’s width to 200 pixels, then the
element’s content box will be 200 pixels wide, and the width of any border or
padding will be added to the final rendered width.

* border-box: In this mode, the width and height properties include content,
padding, and borders i.e if we set an element’s width to 200 pixels, that 200
pixels will include any border or padding we added, and the content box will shrink
to absorb that extra width. This typically makes it much easier to size elements.
JAVASCRIPT JS
* JavaScript was invented by Brendan Eich in 1995.
* JavaScript is the world's most popular programming language.
* JavaScript is the programming language of the Web.
* JavaScript is easy to learn. JavaScript to program the behavior of web pages
* JavaScript is Case Sensitive
.
** JavaScript Can Change HTML Content
document.getElementById("demo").innerHTML = "Hello JavaScript";

** JavaScript Can Change HTML Styles (CSS)


document.getElementById("demo").style.fontSize = "35px";

** JavaScript Can Hide HTML Elements


document.getElementById("demo").style.display = "none";

** In HTML, JavaScript code is inserted between <script> and </script> tags.


<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

* A JavaScript [function] is a block of JavaScript code, that can be executed


when "called" for.
For example, a function can be called when an event occurs, like when the
user clicks a button.

* External JavaScript
External scripts are practical when the same code is used in many different
web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src
(source) attribute of a <script> tag:
Example: <script src="myScript.js"></script>

* External JavaScript Advantages


1. It separates HTML and code
2. It makes HTML and JavaScript easier to read and maintain
3. Cached JavaScript files can speed up page loads
4. To add several script files to one page - use several script tags:

** JavaScript Output
JavaScript can "display" data in different ways:
1. Writing into an HTML element, using innerHTML.
document.getElementById("demo").innerHTML = 5 + 6;
2. Writing into the HTML output using document.write().
document.write(5 + 6);
3. Writing into an alert box, using window.alert().
window.alert(5 + 6);
4. Writing into the browser console, using console.log().
console.log(5 + 6);
5. JavaScript Print
The only exception is that you can call the window.print() method in
the browser to print the content of the current window.
<button onclick="window.print()">Print this page</button>

* let a, b, c; // Declare 3 variables


* a = 5; b = 6; c = a + b; //multiple statements on one line are allowed:
* JavaScript ignores multiple spaces.
* Fixed values are called Literals.
Variable values are called Variables.variables are used to store data
values.
JavaScript keywords are used to identify actions to be performed.

* JavaScript Expressions - An expression is a combination of values,


variables, and operators. 5 * 10
* JavaScript Comments - Code after double slashes //(Single Line Comments) or
between /* and */ is treated as a comment.
* A JavaScript Identifiers /name must begin with:
1.A letter (A-Z or a-z),2. A dollar sign ($) Or an underscore (_)

JS Hero
** Variables
1. An elementary statement is the declaration and initialization of a
variable.
let city = 'Porbandar';
2. Several variables are declared and initialized in 2 program lines:
let city = 'Lubumbashi';
let country = 'Congo';
3. A variable can be reassigned a new value at any time using the equal sign.
let color = 'red';
color = 'green';

** Functions
A function is a block of statements that can be executed as often as you
like. A function can have parameters and can return a value. Functions can be
defined in different ways. Perhaps the most common one is the function declaration.
It starts with the keyword function.
Example: function color() {
return 'red';
}

** Function calls - let x = f();


If the function is assigned to a variable, the function is called via this
variable. Functions are defined once so that they can be used multiple times at
different program points by calling them.

** Parameters
1. Now we get to know functions with parameters. With
function give(input) {
return input;
}
2. we define a function that simply returns the parameter input. Parameters
are variables. With
let result = give('apple');

** Strings - For example, they can be concatenated. This is done with the +
sign. 'Java' + 'Script' results in the string 'JavaScript'.

** Logging
Programming always includes the search for errors. One way to find errors
is logging. During program execution, selective outputs are made. To do this in
JavaScript, use the console.log function:
console.log('Hello console!');
** Logging variables
let scientist = 'Ken Thompson';
console.log(scientist);
The variable scientist is logged. The console outputs 'Ken Thompson'.

** Logging and Strings


Now we want to practice logging together with string concatenation.

---> [Concatenation] is the operation of joining two or more strings together.


There are three ways to concatenate strings in JavaScript:
using the + operator, using the Array#join() method, and using the
String#concat() method12.

The [+] operator can be used to add two strings together, or to add a string and a
non-string value together. For example: "Hello" + "World" returns "HelloWorld", and
"Hello" + 42 returns "Hello42".
You can also use the [+=] operator to append a string to another string. For
example: let str = "Hello"; str += "World"; assigns "HelloWorld" to str.
The [Array#join()] method can be used to join all elements of an array into a
string, using a specified separator. For example: ["a", "b", "c"].join("-") returns
"a-b-c". The default separator is a comma (,). For example: ["a", "b", "c"].join()
returns "a,b,c".
The [String#concat()] method can be used to join two or more strings together,
without changing the original strings. For example: "Hello".concat(" ", "World")
returns "Hello World". However, this method is rarely used because it has more
error cases than the + operator. For example, you will get a TypeError if you try
to call concat() on a null or undefined value2.

** String: charAt()
To get a character from a string at a specified index, use the charAt(index)
method:
** String: trim()
The trim method removes whitespaces from both ends of a string.
** String: indexOf()
To determine the first occurrence of a string within another string, use the
indexOf method:
let n1 = 'bit'.indexOf('it');
** String: indexOf() with from index
The indexOf method allows you to specify the position from which the search
should start. This is done with a second parameter.
let n1 = 'White Rabbit'.indexOf('it', 1);
** String: substr()
The substr method extracts a substring from a string:
let see = 'see and stop'.substr(0, 3);
** String: replace()
The replace method replaces a substring with another:
let str = 'JavaScript';
let newstr = str.replace('Java', 'ECMA');
** Modulo
Another arithmetic operator is modulo. It calculates the remainder of a
division and is represented by %.
let x = 7 % 2; 7 divided by 2 is 3 with remainder 1. x is 1.
** Math
Many mathematical functions are grouped together in the Math object.
For example, Math.sqrt(x) returns the square root and Math.pow(x, y)
calculates x to the power of y.
let y1 = Math.sqrt(9);
let y2 = Math.pow(10, 3);
y1 has the value 3 and y2 has the value 1000 (10³ = 10 * 10 * 10 = 1000).
** min and max
The minimum and maximum of a set of numbers can be calculated with Math.min()
and Math.max():
let min = Math.min(5, 7);
let max = Math.max(3, 9, 2);
** Rounding
If you want to round a number, you can use the Math.round(), Math.floor() and
Math.ceil() functions.
let a = Math.round(5.49);
let b = Math.round(4.5);
let c = Math.floor(5.99);
let d = Math.ceil(4.01);
** Random numbers
Math.random() returns a pseudo-random number between 0 (inclusive) and 1
(exclusive).
let x = Math.random();
x could, for example, get the value 0.6206372241429993. Each call of
Math.random() generates a new random number. The numbers are equally distributed
between 0 and 1.

npm i create-react-app -g
npx create-react-app myworld
npm i -D react-router-dom@latest

npm install axios


$ npm install react
$ npm install prop-types
npm install react-icons

Tailwindcss
npm install -D tailwindcss
npx tailwindcss init

REACT JS NOTES

1. What is React?
. React is a front-end JavaScript library developed by Facebook in 2011.
. It follows the component based approach which helps in building reusable UI
components.
. It is used for developing complex and interactive web and mobile UI.
. Even though it was open-sourced only in 2015, it has one of the largest
communities supporting it.

2. What are the features of React?


Major features of React are listed below:

. It uses the virtual DOM instead of the real DOM.


. It uses server-side rendering.
. It follows uni-directional data flow or data binding.

.SPA . Supports virtual Dom and JSX .everyhing & anything is build using
components

3. List some of the major advantages of React.


Some of the major advantages of React are:
. It increases the application’s performance
. It can be conveniently used on the client as well as server side
. Because of JSX, code’s readability increases
. React is easy to integrate with other frameworks like Meteor, Angular, etc
. Using React, writing UI test cases become extremely easy.

4. What are the limitations of React?


Limitations of React are listed below:

. React is just a library, not a full-blown framework


. Its library is very large and takes time to understand
. It can be little difficult for the novice programmers to understand
. Coding gets complex as it uses inline templating and JSX.

5. What is the purpose of render() in React?

Each React component must have a render() mandatorily. It returns a single React
element which is the representation of the native DOM component. If more than one
HTML element needs to be rendered, then they must be grouped together inside one
enclosing tag such as <form>, <group>,<div> etc. This function must be kept pure
i.e., it must return the same result each time it is invoked.

React Render HTML:

React renders HTML to the web page by using a function called createRoot() and its
method render().

5.I. The createRoot Function:


The creaeRoot() function takes one argument, an HTML element.
The purpose of the function is to define the HTML element where a React component
should be displayed.

5.II. The render Method


The render() method is then called to define the React component that should be
rendered.

5.III. But render where?


There is another folder in the root directory of your React project, named
"public". In this folder, there is an "index.html file".
You'll notice a single " <div> " in the body of this file. This is where our React
application will be " rendered ".

6. DOM AND VIRTUAL DOM?

6.I. DOM stands for ‘Document Object Model’. In simple terms, it is a structured
representation of the HTML elements that are present in a webpage or web app.
. DOM represents the entire UI of your application. The DOM is represented as a
tree data structure. It contains a node for each UI element present in the web
document. It is very useful as it allows web developers to modify content through
JavaScript, also it being in structured format helps a lot as we can choose
specific targets and all the code becomes much easier to work with.

. DOM is the actual document object model that exists in the browser,
while virtual DOM is a lightweight DOM tree constructed in memory. Directly
manipulating the DOM may be slow, while using virtual DOM can improve performance
because virtual DOM updates only the changed parts.

6.II. Virtual DOM


. VDOM is the virtual representation of Real DOM
. React update the state changes in Virtual DOM first and then it syncs with
Real DOM
. Virtual DOM is just like a blueprint of a machine, can do changes in the
blueprint but those changes will not directly apply to the machine.
. Virtual DOM is a programming concept where a virtual representation of a UI is
kept in memory synced with “Real DOM ” by a library such as ReactDOM and this
process is called reconciliation.
. This Virtual DOM works in three simple steps.
1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual
DOM representation.
2. Then the difference between the previous DOM representation and the new one is
calculated.
3. Once the calculations are done, the real DOM will be updated with only the
things that have actually changed.

7. Differences between dom and virtual dom ?

Real DOM
1. It updates slow.
2. Can directly update HTML.
3. Creates a new DOM if element updates.
4. DOM manipulation is very expensive.
5. Too much of memory wastage.

Virtual DOM
1. It updates faster.
2. Can’t directly update HTML.
3. Updates the JSX if element updates.
4. DOM manipulation is very easy.
5. No memory wastage.

8. What is JSX?

JSX stands for JavaScript XML.


JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in React.

8.I Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript
object. Thus to enable a browser to read JSX, first, we need to transform JSX file
into a JavaScript object using JSX transformers like Babel and then pass it to the
browser.
Babel is used to split it to single pages to exceutions.

9. “In React, everything is a component.” Explain.

Components are the building blocks of a React application’s UI. These components
split up the entire UI into small independent and reusable pieces. Then it renders
each of these components independent of each other without affecting the rest of
the UI.

9.I Class Component :

1.A class component requires you to extend from React. Component and create a
render function that returns a React element.
2.It must have the render() method returning JSX (which is syntactically similar
to HTML)
3. Also known as { Stateful components } because they implement logic and state.
4. React lifecycle methods can be used inside class components.
5. Constructor is used as it needs to store state.

9.II Function Component :

1.A functional component is just a plain JavaScript pure function that accepts
props as an argument and returns a React element(JSX).
2.There is no render method used in functional components.
3. Also known as { Stateless components } as they simply accept data and display
them in some form, they are mainly responsible for rendering UI.
4. React lifecycle methods cannot be used in functional components.
5. Constructors are not used.

10. What is a state in React and how is it used?

. States are the heart of React components.


. States are the source of data and must be kept as simple as possible.
. states are the objects which determine components rendering and behavior. They
are mutable unlike the props and create dynamic and interactive components. They
are accessed via this.state().

. The state is a built-in React object that is used to contain data or information
about the component.
. The state is both read and write

11. What is Props?

. Props is the shorthand for Properties in React.


. They are read-only components which must be kept pure i.e. immutable (not
changable).
. They are always passed down from the parent to the child components throughout
the application.
. A child component can never send a prop back to the parent component. This help
in maintaining the unidirectional data flow and are generally used to render the
dynamically generated data.

11.I What is the advantage of props in React?

. Props are used to store data that can be accessed by the children of a React
component.
. They are part of the concept of reusability.
. When we want to share the same behavior among different components, the render
props pattern enables us to minimize code repetitions.

11.II What are the disadvantages of props in React?

. Drawbacks of Using Props for State Management


. This can make your code more difficult to maintain and understand, as each
intermediate component needs to forward the props. Lack of State Control: Props are
read-only, and child components cannot modify the props they receive from their
parent component.

. Prop drilling is a technique for passing data from parent components to child
components. It is effective for sharing data, but it has several drawbacks that can
make code difficult to maintain and develop.

. To overcome these drawbacks, you can use alternatives like React Context, Redux,
and MobX. These solutions provide a more centralized way to manage data, which can
make code more maintainable and scalable.

11.I Differentiate between states and props.

Conditions State Props


1. Receive initial value from parent component Yes Yes
2. Parent component can change value No Yes
3. Set default values inside component Yes Yes
4. Changes inside component Yes No
5. Set initial value for child components Yes Yes
6. Changes inside child components No Yes

. the main significant difference between states and props is that props are used
to transfer data from a parent component to a child whereas states are used to
manage the data inside a component.

12. Differentiate between stateful and stateless components.

Statefull Component
1. Stores info about component’s state change in memory
2. Have authority to change state
3. Contains the knowledge of past, current and possible future changes in state
4. Stateless components notify them about the requirement of the state change, then
they send down the props to them.

Stateless Component
1. Calculates the internal state of the components
2. Do not have the authority to change state
3. Contains no knowledge of past, current and possible future state changes
4. They receive the props from the Stateful components and treat them as callback
functions.

13. Explain the lifecycle methods of React components in detail.

Each component in React has a lifecycle which you can monitor and manipulate during
its three main phases. The three phases are: Mounting, Updating, and Unmounting.

React Components Lifecycle:

1.Mounting - We call these methods in the following order when an element is being
created and inserted into the DOM:
2.Updating - We call the methods in this phase whenever State or Props in a
component get updated. This allows the React application to “react” to user inputs,
such as clicks and pressing keys on the keyboard, and ultimately create a
responsive web user interface.
3.Unmounting - This is the last phase of the life-cycle of the component where the
component is unmounted from the DOM. This phase has only one method:

Some of the most important lifecycle methods are:

1. componentWillMount() – Executed just before rendering takes place both on the


client as well as server-side.
2. componentDidMount() – Executed on the client side only after the first render.
3. componentWillReceiveProps() – Invoked as soon as the props are received from the
parent class and before another render is called.
4. shouldComponentUpdate() – Returns true or false value based on certain
conditions. If you want your component to update, return true else return false. By
default, it returns false.
5. componentWillUpdate() – Called just before rendering takes place in the DOM.
6. componentDidUpdate() – Called immediately after rendering takes place.
7. componentWillUnmount() – Called after the component is unmounted from the DOM.
It is used to clear up the memory spaces.

14. What is a Hook?

. Hooks allow function components to have access to state and other React
features. Because of this, class components are generally no longer needed.
. Hooks will not work in React class components.
. The useState Hook can be used to keep track of strings, numbers, booleans,
arrays, objects, and any combination of these!

* There are 3 rules for hooks:

Hooks can only be called inside React function components.


Hooks can only be called at the top level of a component.
Hooks cannot be conditional

14.I What is useState in ReactJS?

. useState is React Hook that allows you to add state to a functional component.
. The Hook takes an initial state value as an argument and returns an updated
state value whenever the setter function is called.
. It returns an array with two values: the current state and a function to update
it.

* What is the benefit of useState?

The useState hook is simple and easy to use for managing simple state values that
don't require complex updates. It is best used for state that only needs to be
updated in one way, such as a counter that only needs to be incremented or
decremented.

* EX: 1. import { useState } from "react";


Initialize useState:
2. const [color, setColor] = useState("");
Update State:
3. <button
type="button"
onClick={() => setColor("blue")}
>Blue</button>

14.II React useEffect

. The useEffect Hook allows you to perform side effects in your components.
. Some examples of side effects are: fetching data, directly updating the DOM, and
timers.

. useEffect accepts two arguments. The second argument is optional.


useEffect(<function>, <dependency>)
. The Effect Hook, just like the name implies, carries out an effect each time
there is a state change. By default, it runs after the first render and every time
the state is updated.

* how to control the useEffect there are 3ways to overcome :

1. without the dependenecy List (no matter which state changes the rendering will
happens(useEffect will be called)).
2. Empty dependenceyList (avoiding the rendereing) only one once
3. with dependenceyList.

14.III React useContext

. This hook allows you to access the context within a component. It's useful for
accessing global data and avoiding prop drilling.
. It is used to share data. It is used to manage data and state
. is a way to manage state globally.

What is the benefit of useContext?

useContext is best used when you need to share data across multiple components at
different levels of the component tree, especially when passing props becomes
cumbersome and difficult to manage.

14.IV React useRef

. The useRef Hook allows you to persist values between renders.


. It can be used to store a mutable value that does not cause a re-render when
updated.
. It can be used to access a DOM element directly.

14.V React useReducer:

. This hook is used for managing complex state logic. It is similar to useState
but allows you to manage state through a reducer function.
. The useReducer Hook accepts two arguments.

1. useReducer(<reducer>, <initialState>)

. The reducer function contains your custom state logic and the initialStatecan be
a simple value but generally will contain an object.
. The useReducer Hook returns the current stateand a dispatchmethod.

VI. UseMemo VII. UseCallback.

15. Redux

. Redux is a state management framework that can be used with React.


. Although Redux and React are commonly used together, they are independent of
each other.

15.1. What is the Redux Store?

The global state of an application is stored in an object tree within a single


store .

The Redux store is the main, central bucket which stores all the states of an
application. It should be considered and maintained as a single source of truth for
the state of the application.

If the store is provided to the App.js (by wrapping the App component within the
<Provider> </Provider> tag)
then all its children (children components of App.js) can also access the state of
the application from the store. This makes it act as a global state.

15.2. 2. What Are Actions in Redux?

The only way to change the state is to emit an action, which is an object
describing what happened.
. state in Redux is read-only. This helps you restrict any part of the view or any
network calls to write/update the state directly.
. Instead, if anyone wants to change the state of the application, then they'll
need to express their intention of doing so by emitting or dispatching an action.

Another way for Redux:

React redux maintains the state of the application in a single place called Redux
store. React component can get the latest state from the store as well as change
the state at any time. Redux provides a simple process to get and set the current
state of the application and involves below concepts.

Store − The central place to store the state of the application.

Actions − Action is an plain object with the type of the action to be done and the
input (called payload) necessary to do the action. For example, action for adding
an item in the store contains ADD_ITEM as type and an object with item’s details as
payload.

Reducers − Reducers are pure functions used to create a new state based on the
existing state and the current action. It returns the newly created state. For
example, in add item scenario, it creates a new item list and merges the item from
the state and new item and returns the newly created list.

Action creators − Action creator creates an action with proper action type and data
necessary for the action and returns the action.

The Dispatch function - accepts an object that represents the type of action we
want to execute when it is called.

The second one is “payload”, - Payload stores the additional information about
what happened. It is not a compulsion to include “payload” in the object. It is
entirely up to you but we should always try to pass only the necessary information
to the action object and try to keep it as light as possible.

In Redux, dispatch needs to tell the app that the state has been updated. This
happens through listeners and subscriptions. In the useReducer hook, React
recognizes that the state was updated and re-renders the component. The updated
state is then returned to the component from where the useReducer hook was called.

Why Redux?

. State transfer between components is pretty messy in React since it is hard to


keep track of which component the data is coming from. It becomes really
complicated if users are working with a large number of states within an
application.
. Redux solves the state transfer problem by storing all of the states in a single
place called a store. So, managing and transferring states becomes easier as all
the states are stored in the same convenient store. Every component in the
application can then directly access the required state from that store.

LogRocket websit:

What is Redux?
Redux is a predictable state container for JavaScript applications. It helps you
write apps that behave consistently, run in different environments (client, server,
and native), and are easy to test. Redux manages an application’s state with a
single global object called Store.
Redux solves the state transfer problem by storing all of the states in a single
place called a store. So, managing and transferring states becomes easier as all
the states are stored in the same convenient store. Every component in the
application can then directly access the required state from that store.

Redux reducers:
Reducers are pure functions that take the current state of an application, perform
an action, and return a new state. The reducer handles how the state (application
data) will change in response to an action

Redux store:
The store is a “container” (really, a JavaScript object) that holds the application
state, and the only way the state can change is through actions dispatched to the
store. Redux allows individual components to connect to the store.

It is highly recommended to keep only one store in any Redux application. You can
access the stored state, update the state, and register or unregister listeners via
helper methods. Basically, the components get to update the store via actions and
then subscribe to the changes to the store so they know when to re-render:

16. Introduction to Axios:

Axios, which is a popular library is mainly used to send asynchronous HTTP requests
to REST endpoints. This library is very useful to perform CRUD operations.

. This popular library is used to communicate with the backend. Axios supports the
Promise API, native to JS ES6.

. Using Axios we make API requests in our application. Once the request is made we
get the data in Return, and then we use this data in our project.

. The same tasks can also be performed by using AJAX, but Axios provide you more
functionality and features and that helps you in building your application quickly.

. Axios is a promise-based library, so you need to implement some promise-based


asynchronous HTTP requests. jQuery and AJAX also perform the same job but in React
project React handles each and everything in its own virtual DOM, so there is no
need to use jQuery at all.

* Response Objects in Axios:


When you send a request to the server, you receive a response object from the
server with the properties given below…

1. DATA: You receive data from the server in payload form. This data is returned in
JSON form and parse back into a JavaScript object to you.
2. STATUS: You get the HTTP code returned from the server.
statusText: HTTP status message returned by the server.
3. HEADERS: All the headers are sent back by the server.
4. CONFIG: original request configuration.
5. REQUEST: actual XMLHttpRequest object.

* Error Object:
You will get an error object if there will be a problem with the request. Promise
will be rejected with an error object with the properties given

1. message: Error message text.


2. response: Response object (if received).
3. request: Actual XMLHttpRequest object (when running in a browser).
4. config: Original request configuration.

* Features of Axios Library

1. JSON data is transformed automatically.


2. It transforms the request and response data.
3. Useful in making HTTP requests from Node.js
4. It makes XMLHttpRequests from the browser.
5. Provide client-side support for protecting against XSRF.
6. Supports promise API.
7. Ability to cancel the request.

* Shorthand Methods in Axios: Below are some shorthand methods of Axios…

axios.request(config)
axios.head(url[, config])
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.delete(url[, config])
axios.options(url[, config])
axios.patch(url[, data[, config]])

17. React Router

We wrap our content first with <BrowserRouter>.

Then we define our <Routes>. An application can have multiple <Routes>. Our basic
example only uses one.

<Route>s can be nested. The first <Route> has a path of / and renders the Layout
component.

The nested <Route>s inherit and add to the parent route. So the blogs path is
combined with the parent and becomes /blogs.

The Home component route does not have a path but has an index attribute. That
specifies this route as the default route for the parent route, which is /.

Setting the path to * will act as a catch-all for any undefined URLs. This is great
for a 404 error page.

Pages / Components
The Layout component has <Outlet> and <Link> elements.

The <Outlet> renders the current route selected.

<Link> is used to set the URL and keep track of browsing history.

17.II Suspense :

is a React feature that allows for components to be loaded asynchronously. It is


used in conjunction with React. lazy . Suspense is also used to display a loading
indicator while the component is being fetched, or it can be used to render a
fallback component if the component fails to load.

“React lazy loading.”


It can help you improve your website's speed by loading only the necessary
components and resources when they are needed, resulting in faster initial page
load times and improved user experience.

What are higher-order components in react?

In React, a higher-order component is a function that takes a component as an


argument and returns a new component that wraps the original component.

UseState EX :
import React, { useState } from 'react';

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

const increment = () => {


setCount(count + 1);
};

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

UseEffect EX :
import React, { useState, useEffect } from 'react';

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

useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

UseContext EX:
import React, { useContext } from 'react';
import MyContext from './MyContext';

function MyComponent() {
const contextData = useContext(MyContext);
return <div>{contextData}</div>;
}

UseRef EX:
import React, { useRef } from 'react';

function TextInputWithFocusButton() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};

return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}

Redux Setup:

1.Setting up a store with Redux toolkit

import { configureStore } from '@reduxjs/toolkit'


import counterReducer from './counterReducer'

const store = configureStore({


reducer: {
counter: counterReducer,
},
})

export default store

2.Creating an action using Redux Toolkit

const addTodo = createAction('INCREMENT')


addTodo({ val: 5 })
// {type : "INCREMENT", payload : {val : 5}})

3.Creating the reducer with Redux Toolkit

import { createAction, createReducer } from '@reduxjs/toolkit'

const increment = createAction('counter/increment')


const incrementByAmount = createAction('counter/incrementByAmount')

const initialState = { value: 0 }

const counterReducer = createReducer(initialState, (builder) => {


builder
.addCase(increment, (state, action) => {
state.value++
})
.addCase(incrementByAmount, (state, action) => {
state.value += action.payload
})
})

// a case without toolkit, notice the .map to create a new state


case 'TOGGLE_TODO': {
const { index } = action.payload
return state.map((todo, i) => {
if (i !== index) return todo
return {
...todo,
completed: !todo.completed,
}
})
}

// a case with toolkit, notice the mutation which is taken care internally
.addCase('TOGGLE_TODO', (state, action) => {
const todo = state[action.payload.index]
// "mutate" the object by overwriting a field
todo.completed = !todo.completed
})

4.Redux middleware
function simpleMiddleware({ getState, dispatch }) {
return function(next){
return function(action){
// processing
const nextAction = next(action);
// read the next state
const state = getState();
// return the next action or you can dispatch any other action
return nextAction;
}
}
}

You might also like