WPT Notes
WPT Notes
Duration: 108 hours (48 classroom hours + 48 lab hours + 12 revision/practice hours)
Objective: To introduce the students to HTML, CSS, JavaScript, XML, JSON, Ajax, Node.js, Express.js,
React, React-Redux, and practical relevance of all these technologies.
Text Books:
Fundamentals of Web Development, 1e, by Randy Connolly, Ricardo Hoar / Pearson
MERN Quick Start Guide – Build web applications with MongoDB, Express.js, React, and Node by
Eddy Wilson Iriarte Koroliova / Packt
References:
Internet & World Wide Web : How to Program by Paul Deitel, Henry Deitel & Abbey Deitel /
Pearson Education
XML - How to Program by Deitel et al / Pearson Education
Ajax in Action by Dave Crane, Eric Pascarello / Dreamtech Press
JavaScript: The Good Parts by Douglas Crockford / O'Reilly
Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React, and Node by
Vasan Subramanian / Apress
Web Application Security: A Beginner's Guide by Bryan Sullivan & Vincent Liu / Tata McGraw Hill
W3Schools Tutorials [ https://www.w3schools.com/ ]
Mozilla Developer Network Web Development Tutorials [ https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web ]
Curated Tutorial Links on ES6, React, etc. [ https://github.com/markerikson/react-redux-links ]
Lab:
Exploring different browsers
o Mozilla Firefox, Google Chrome, Safari
Exploring different text editors
o Windows: Notepad++, Linux: Gedit or Vim or Emacs
Session 2: HTML
Lecture:
Introduction to HTML5
Introduction to basic HTML Tags
o Alignment, Headings, Anchor, Paragraph, Image, Lists, Tables, and iFrames
HTML5
o New features in HTML5
o New elements, new attributes, link relations, microdata, ARIA accessibility, objects,
events, and Canvas tags
o HTML5 Validation
o Audio & Video Support
o Geo-location Support
HTML Forms & Controls
o Input, Text Area, Radio Button, Checkbox, Dropdown, Submit, Reset, Button, etc.
Introduction to Document Object Model (DOM)
Lab:
Create a HTML form for building your resume.
Session 4: JavaScript
Lecture:
Introduction to JavaScript
Variables in JavaScript
Statements, Operators, Comments, Expressions, and Control Structures
JavaScript Scopes
Strings, String Methods
Numbers, Number Methods
Boolean Values
Dates, Date Formats, Date Methods
Arrays, Array Methods
Lab:
Practice writing basic JavaScript programs for better understanding of the language constructs
Sessions 5 & 6: JavaScript
Lecture:
Objects, Object Definitions, Object Properties, Object Methods, Object Prototypes
Functions, Function Definitions, Function Parameters, Function Invocation, Function Closures
Introduction to Object Oriented Programming in JS
o Method, Constructor, Inheritance, Encapsulation, Abstraction, Polymorphism
Lab:
Write a JavaScript program to sort a list of elements by implementing a sorting algorithm.
Write a JavaScript program to list the properties of a JavaScript object.
Session 9: jQuery
Lecture:
Introducing to jQuery
jQuery selectors
jQuery events
jQuery animation effects
jQuery DOM traversal and manipulation
Data attributes and templates
jQuery DOM utility functions
jQuery plugins
Lab:
Write a jQuery program to get a single element from a selection of elements of a HTML page.
You are having sample data for the link. Write jQuery code to change the hyperlink and the
text of an existing link.
Write a jQuery program to attach a click and double-click events to all <p> elements.
Write a jQuery program to hide all headings on a page when they are clicked.
o Also find the position of the mouse pointer relative to the left and top edges of the document.
What is HTML?
• HTML(Hyper Text Markup Language)
is a language for describing web pages.
not a programming language
uses markup tags to describe web pages.
• Most Web documents are created using HTML.
Documents are saved with extension .html or .htm.
• Markup?
Markup Tags are strings in the language surrounded by a < and a > sign.
Opening tag: <html> Ending tag: </html>
Not case sensitive.
Can have attributes which provide additional information about HTML elements on
your page. Example
o <body bgcolor="red">
o <table border="0">
3
HTML
• An HTML document appears as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>
HTML Head Section: contain information about the document. The browser does not
display this information to the user. Following tags can be in the head section:
<base>, <link>, <meta>, <script>, <style>, and <title>.
HTML Body Section: defines the document’s body. Contains all the contents of the
document (like text, images, colors, graphics, etc.).
<HTML>
<HEAD>
<TITLE>Body Tag</TITLE>
</HEAD>
<BODY BGCOLOR="pink" text="red"
alink="green" link="yellow">
<a href="body.html">background</a>
color of the page is pink. and text color is red
</BODY>
</HTML>
5
<html>
<body>
<b>This is in bold font</b>
<i>This text is in Italics</i>
<u>This text is Underlined</u>
<small>This is small text.</small>
<font size=7>This text is very large</font>
<font color=”Blue”>This is Blue Text.</font>
<strike>This is strikethrough style text</strike>
The chemical formula of water is h<sub>2</sub>o.
A simple formula for a parabola is y = x<sup>2</sup>.
</body>
</html>
<html>
<head><title>This is the first html page</title>
<body>This is the first html page created
<h1 align=”left”>This is level 1 heading</h1>
<h2 align=”right”>This is level 2 heading</h2>
<h3 align=”center”>This is level 3 heading</h3>
</body>
</head>
</html>
<body> <p>
This paragraph contains a lot of lines
in the source code,
but the browser ignores it. </p>
<hr size="2" width="50%" color="blue“ align = “left” > <p>
Notice the horizontal rule occupying 50 % of the window width.
</p> This paragraph contains <br> line breaks in the
source code <br> so this is the third line displayed within the paragraph.
</body>
9
• Select the type of numbering system with the type attribute. Example:
o A-Uppercase letters. <OL TYPE=A>
o a-Lowercase letters. <OL TYPE=a>
o I-Uppercase Roman letters
o i-Lowercase Roman letters
o 1-Standard numbers, default
10
• To change the type of bullet used throughout the list, place the TYPE attribute
in the <UL> tag at the beginning of the list.
DISC (default) gives bullet in disc form.
SQUARE gives bullet in square form.
CIRCLE gives bullet in circle form.
<ul>
<li type=‘disc’>Latte</li>
<li type=‘square’>Expresso</li>
<li type=‘circle’>Mocha</li>
</ul>
11
Adding Image
• Images are added into a document using <img> tag.
• Attributes of <img> tag are:
alt: Alternative text to display for non-graphical browsers.
align: Image horizontal alignment. Valid values: left, right, center.
width/Height: Sets the width and height of the image.
src: Specifies the image path or source.
12
Table
• Use <table> tag to create a table.
• Table Attributes:
Border: <table border=“2”>………</table>
Align: defines the horizontal alignment of the table element.
o Values of the align attribute are right, left and center. <table align=“center”>
Width: defines the width of the table element.
o <table width=“75%”>………</table>
o <table width=“400”>………</table>
• Example:
<table border="1">
<tr border="1">
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
13
Table Data
• You can insert a bgcolor attribute in a <table>, <td>, <th> or <tr> tag to set the
color of the particular element.
<table bgcolor="cyan">
<tr bgcolor="blue">
<table bgcolor="cyan">
<tr bgcolor="blue">
<th bgcolor="red">Header 1</th> <th>Header 2</th>
</tr>
<tr> <td bgcolor="green">data 1</td> <td>data 2</td> </tr>
</table>
14
<ul>
<li><a href=home.html>mumbai</a></li>
<li><a href=home.html>pune</a></li>
<li><a href=home.html>nasik</a></li>
</ul>
<table border=1>
<tr><th>team<th>points<th>grade</tr>
<tr><td><a href=home.html>mumbai</a></td><td>90</td><td>a</td></tr>
<tr><td><a href=home.html>pune</a></td><td>86</td><td>b</td></tr>
<tr><td><a href=home.html>nasik</a></td><td>80</td><td>c</td></tr>
</table>
15
16
Text Field
• Single Line Text Fields: used to type letters, numbers, etc. in a form.
<INPUT TYPE=”type” NAME=”name” SIZE=”number” VALUE=”value” maxlength=n>
Eg:
<form>
First name: <input type="text" name="firstname“ value=“fname>
Last name:<input type="text" name="lname">
</form>
Check Box
• Lets you select one or more options from a limited number of choices.
<input type=“checkbox” name=“name” value=“value” [checked] [disabled]> Checkbox
Label
Content of value attribute is sent to the form's action URL.
Radio Buttons
<input type=“radio” name=“name” value=“value” [checked] [disabled]> Radio Button Label
• Content of the value attribute is sent to the form's action URL.
<form>
<input type="radio" name="sex" value="male"/>Male<br>
<input type="radio" name="sex" value="female"/> Female
</form>
Hidden Field
• Allows to pass information between forms:
• <input type=“hidden” name=“name” size=“n” value=“value”/>
• <input type=“hidden” name=“valid_user” size=“5” value=“yes”/>
18
Password Fields
• <input type=“password” name=“name” size=n value=“value” [disabled]>
Eg: Enter the password:<input type=“password” name=“passwd” size=20 value=“abc”>
<FORM>
Please select file that you want to upload:
<INPUT name=“file” type=“file”> <BR>
<INPUT type=“submit” >
</FORM>
Action Buttons
• To add a button to a form use:
• <input type=“button” name=“btnCalculate” value=“Calculate”/>
• To submit the contents of the form use:
• <input type=“submit” name=“btnSubmit” value=“Submit”/>
• To reset the field contents use:
• <input type=“reset” name=“btnReset” value=“Reset”/>
19
Drop-Down List
<select name=“name” multiple=“true/false” size=n [disabled]>
<option [selected] [disabled] [value]>Option 1</option>…
</select>
Multiple: States if multiple element selection is allowed.
Size: Number of visible elements.
Disabled: States if the option is to be disabled after it first loads.
Eg:
<form>
<select multiple size="3" name="pref">
<option value="ih" selected>Internet-HTML</option>
<option value="js">Javascript</option>
<option value="vbs">VBscript</option>
<option value="as">ASP</option>
<option value="xm">XML</option>
<option value="jv">JAVA</option>
<option value="jsp">jsp</option>
</select>
</form>
<html><head><title>form examples</title></head>
<body bgcolor="pink">
<form name="form1" action="store.html" method="post">
Complete example
<p>
<strong>Enter first name</strong>: <input name="username">
<strong>Enter lastname</strong>: <input maxlength="30" name="surname"></p>
<p><strong>Enter address:</strong>
<textarea name="addr" rows="3" readonly value="sjdshd"></textarea>
<br><br>
<strong>Select the training programs attended:</strong>
<input type="checkbox" value="internet/html" name="internet-html"> Internet/HTML
<input type="checkbox" checked value="c programming" name="c-programming">C Programming
<input type="checkbox" value="dbms-sql" name="dbms-sql"> DBMS-SQL </p>
<p><strong>Select the stream you belong to:</strong>
<input type="radio" value="science" name="s-grp"> Science
<input type="radio" value="arts" name="s-grp"> Arts
<input type="radio" value="commerce" name="s-grp"> Commerce
<input type="radio" value="oth2" name="s-grp">Engineering </p>
<strong>Which training program would you like to attend ?</strong>
<select size="5" multiple name="pref">
<option value="ih" selected>Internet-HTML
<option value="js">Javascript
<option value="vbs">VBscript
<option value="as">ASP
<option value="xm">XML
<option value="jv">JAVA
<option value="jsp">jsp</option>
</select> <br>
<input type="button" value="exit" name="but">
<input type="submit" value="save">
<input type="reset" value="reset">
</form></body></html>
HTML5
• Required - A "Required Field" is a field that must be filled in with value before
submission of a form
• <input name="name" type="text" required />
• Email - This field is used to check whether the string entered by the user is valid
email id or not.
<input id="email" name="email" type="email" />
• Search - used for search fields (behaves like a regular text field).
<input id="mysearch" type="search" />
• Tel - used for input fields that should contain a telephone number.
<input type="tel" name="usrtel">
• url - is used for input fields that should contain a URL address.
Depending on browser support, the url field can be automatically validated when
submitted.
• color – displays a color palette
New Form elements
• Number - used for input fields that should contain a numeric value.
Min and max parameters provided to limit the values.
Browser will treat it as simple textfield if it doesn’t support this type.
<input id="movie" type="number" value="0"/>
<input type="number“ min="0“ max="50“ step="2“ value="6">
• Range - used for input fields that should contain a value within a range
Browser will treat it as simple textfield if it doesn’t support this type
<input id="test" type="range"/>
<input type="range" min="1" max="20" value="0">
<input id="country_name"
name="country_name"
type="text“
list="country" />
<datalist id="country">
<option value="Australia">
<option value="Austria">
<option value="Algeria">
<option value="Andorra">
<option value="Angola">
</datalist>
Audio
• Until now, there has never been a standard for playing audio on a web page.
Today, most audio is played through a audio plugin (like Microsoft Windows Media
player, Microsoft Silverlight ,Apple QuickTime and the famous Adobe Flash).
However, not all browsers have the same plugins.
HTML5 specifies a standard way to include audio, with the audio element; The audio
element can play sound files, or an audio stream.
Currently, there are 3 supported formats for the audio element: Ogg Vorbis, MP3,
.webm and WAV
Other properties like auto play, loop, preload area also available
<audio controls>
<source src="vincent.mp3" type="audio/mpeg"/>
<source src="vincent.ogg" type="audio/ogg"/>
</audio>
Video
• Until now, there hasn't been a standard for showing video on a web page.
Today, most videos are shown through a plugin (like Flash). However, not all
browsers have the same plugins.
HTML5 specifies a standard way to include video with the video element
Supported video formats for the video element : Ogg, MP4, WebM, .flv, .avi
Attributes : width, height, poster, autoplay, controls, loop, src
Canvas
• A canvas is a rectangle in your web page within which you can use
JavaScript to draw shapes
Canvas can be used to represent something visually in your browser like Simple
Diagrams, Fancy user interfaces, Animations, Charts and graphs, Embedded
drawing applications, Working around CSS limitations
The canvas element has several methods for drawing paths, boxes, circles,
characters, and adding images.
The canvas element has no drawing abilities of its own. All drawing must be done
inside a JavaScript
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
</script>
New Semantic Elements
Fat footer on
the w3c site
33
What is CSS?
• Cascading Styles Sheets - a way to style and present HTML.
HTML deals with content and structure, stylesheet deals with formatting and
presentation of that document.
Allows to control the style and layout of multiple Web pages all at once.
• Example:
Messy HTML
<font color="#FF0000" face="Verdana, Arial, Helvetica, sans-serif">
<strong>This is text</strong></font>
• Why CSS?
saves time
Pages load faster
Easy maintenance
Superior styles to HTML
34
CSS Syntax
• A CSS rule has two parts: a selector, and one or more declarations:
36
linked_ex2.css
37
Types of selectors
• HTML selectors
Used to define styles associated to HTML tags. – already seen!!!!
• Class selectors
Used to define styles that can be used without redefining plain HTML tags.
• ID selectors
Used to define styles relating to objects with a unique id
ID Selector & Style Sheet Classes
<style>
H1.myClass {color: blue}
.myOtherClass { color: red; text-align:center}
</style>
<body style="background: white; color:green">
<H1 class="myClass">This text would be blue</H1>
<p class="myOtherClass">The text would be in red</P>
<html> <head> <H3 class="myOtherClass">This is level 2 heading</H3>
<style> <table class=myotherClass border width=100%>
#para1 { <td>Data 1</td><td>Data 2</td></table>
text-align:center; <h3>This is Level 4 Heading, without style</h3>
color:red; <h1>This is again Level 1 heading with default styles</h1>
}
</style> </head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the
style.</p>
</body>
</html>
CSS Styling
Lesson 10. Cascading Style Sheets
CSS Background
• CSS background properties are used to define the background effects of an
element.
• CSS properties used for background effects:
body {
background: #00ff00 url("smiley.gif") no-repeat fixed center;
}
<html>
<head><style>
body {
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
margin-right:200px;
}
</style> </head>
<body>
<h1>Hello World!</h1>
<p>Background no-repeat, set position example.</p>
<p>Now the background image is only shown once, and positioned away from the text.</p>
<p>In this example we have also added a margin on the right side, so the background image will never
disturb the text.</p>
</body></html>
CSS Text
• CSS Text Properties
<style>
h1 {text-decoration:overline;}
h2 {text-decoration:line-through;}
h3 {text-decoration:underline;}
</style>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
Demo : <style>
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
</style>
<body>
<p class="uppercase">This is some text.</p>
<p class="lowercase">This is some text.</p>
<p class="capitalize">This is some text.</p>
</body>
<head> <style>
h1 {text-align:center;color:#00ff00;}
p.date {text-align:right;}
p.main {text-align:justify;}
p.ex {color:rgb(0,0,255);}
p.indent {text-indent:50px;}
</style> </head>
<body>
<h1>Hello World!</h1>
<p class="date"> Sep 2013</p>
<p class="main indent">The CSS property text-align corresponds to the attribute align used in old versions of
HTML. Text can either be aligned to the left, to the right or centred. In addition to this, the value justify will
stretch each line so that both the right and left margins are straight. You know this layout from for example
newspapers and magazines. </p>
<p class="ex">The property text-decoration makes it is possible to add different "decorations" or "effects" to
text. </p>
</body>
More examples
• P { word-spacing:30px; }
• p.small {line-height:70%;}
• p.big {line-height:200%;}
• h1 {letter-spacing:2px;}
• h2 {letter-spacing:-3px;}
• Example:
p.normal {font-weight:normal;}
p{font-family:"Times New Roman", Times;}
p.italic {font-style:italic;}
h1 {font-size:40px;}
p.small { font-variant:small-caps; }
Styling lists
• The CSS list properties allow you to: Example:
Set different list item markers for ordered lists ul.circle {list-style-type:circle}
ol.upper-roman {list-style-type:upper-roman}
Set different list item markers for unordered lists ul { list-style-image: url('sqpurple.gif'); }
Set an image as the list item marker
• CSS List Properties
list-style-image Specifies an image as the list-item marker
list-style-position Should the list-item markers appear inside or outside the content flow
list-style-type Specifies the type of list-item marker
<html>
<head>
<style> Image and table
ul { list-style-image:url('sqpurple.gif’); }
</style> img {
</head> float: right;
<body> margin: 0 0 10px 10px;
<ul> }
<li>Coffee</li>
<li>Tea</li> table{
<li>Coca Cola</li> border: 1px solid black;
</ul> border-collapse: collapse;
</body> }
• Padding defines the inner distance of elements to the end of the box.
• Example
padding-top:25px; <head><style>
padding-bottom:25px; p { background-color:yellow; }
padding-right:50px; p.padding {
padding-left:50px; padding:25px 25px 50px 50px;
}
</style></head>
<body>
<p>This is a paragraph with no specified padding.</p>
<p class="padding">This is a paragraph with specified paddings.</p>
</body>
Margins
• Margins allow you to put a bigger distance between your elements
the margin is an outer, invisible border around your element.
<style type="text/css">
You can define the margins for a
.box {
box individually or combine them
background-color: DarkSeaGreen;
into one statement.
width: 100px;
height: 100px;
.box { ….; margin: 10px 10px 10px 10px; }
margin-top: 10px;
margin-right: 5px;
margin-bottom: 10px;
margin-left: 5px;
}
</style>
<div class="box"> Box </div>
<head>
<style>
p.ex1 {margin:2cm 4cm 3cm 4cm}
</style>
</head>
<body>
<p>A paragraph with no specified margins.</p>
<p class="ex1">A paragraph with specified margins.</p>
<p>A paragraph with no specified margins.</p>
</body>
CSS Border
• The border property is a shorthand for the following individual border
properties: border-width, border-style (required), border-color
<style type="text/css">
.box {
width: 100px;
height: 100px;
border-color: Blue;
border-width: 2px;
border-style: solid;
} p { border: 5px solid red; }
</style>
<div class="box">
Hello, world!
</div>
<style> #rcorners3 {
#rcorners1 { border-radius: 25px;
border-radius: 25px; background: url(paper.gif);
background: #8AC007; background-position: left top;
padding: 20px; background-repeat: repeat;
width: 100px; padding: 20px;
height: 100px; width: 100px;
} height: 100px;
#rcorners2 { }
border-radius: 25px; </style>
border: 2px solid #8AC007; <p id="rcorners1">Rounded corners!</p>
padding: 20px; <p id="rcorners2">Rounded corners!</p>
width: 100px; <p id="rcorners3">Rounded corners!</p>
height: 100px;
}
Shadow Effects
• You can add shadow to text and to elements.
text-shadow property applies shadow to text.
box-shadow property applies shadow to elements.
<style>
.c1{text-shadow: 2px 2px;}
.c2{text-shadow: 2px 2px red;}
.c3{text-shadow: 2px 2px 5px red;}
.c4{color: white; text-shadow: 2px 2px 4px #000000;}
</style>
<p class="c1">para-1</p>
<p class="c2">para-2</p>
<p class="c3">para-3</p>
<style>
<p class="c4">para-4</p>
.c1{box-shadow: 10px 10px;}
.c2{box-shadow: 10px 10px grey;}
.c3{ box-shadow: 10px 10px 5px grey;}
p { width: 300px; height: 100px; padding: 15px; background-color:
yellow; }
</style>
<p class="c1">para-1</p>
<p class="c2">para-2</p>
<p class="c3">para-3</p>
Javascript
Overview
• JavaScript is Netscape's cross-platform, object-based scripting language
JavaScript code is embedded into HTML pages
It is a lightweight programming language
Client-side JavaScript extends the core language by supplying objects to control a
browser and its Document Object Model
• Why use Javascript?
Provides HTML designers a programming tool :
Puts dynamic text into an HTML page
Reacts to events
Reads and writes to HTML elements :
Can be used to perform Client side validation
<html>
The <SCRIPT> tag <head> </head>
<body>
<SCRIPT> <script type="text/javascript">
JavaScript statements … document.write("<H1>Hello World!</H1>");
</SCRIPT> alert(“some message”);
console.log(“some message”);
</script>
</body></html>
Embedding JavaScript in HTML
<html>
• Where to Write JavaScript?
<head>
Head Section <script type="text/javascript">
Body Section function message() {
alert(“Hello World")
External File }
</script>
<html> </head>
<head></head> <body onload="message()">
<body > </body>
<script language=“javascript"> </html>
document.write(“Hello World!“)
</script>
</body>
</html>
<head>
<script src="common.js">
<!– no javascript statements //common.js file contents
</ script> var msg
</head> msg=“<h1>in external file</h1>"
<body>
<script>
document.write("display value of a variable”+msg)
</script>
</body>
• Variables that exist only inside a function are called Local variables
• Variables that exist throughout the script are called Global variables
Their values can be changed anytime in the code and even by other functions
Predefined Functions
• isFinite: evaluates an argument to determine if it is a finite number.
isNaN(0) //false
• Parseint and parsefloat isNaN('123') //false
isNaN('Hello') //true
Returns a numeric value for string argument.
parseInt (str)
parseFloat (str)
parseInt() interprets any
parseInt("3 blind mice") // => 3 number beginning with “0x” or
parseFloat(" 3.14 meters") // => 3.14 “0X” as hexadecimal no
parseInt("-12.34") // => -12
parseInt("0xFF") // => 255
parseInt("0xff") // => 255
parseInt("-0XFF") // => -255
parseFloat(".1") // => 0.1
parseInt("0.1") // => 0
2.4: JavaScript Functions
parseInt(".1") // => NaN: integers can't start with "."
parseFloat("$72.47"); // => NaN: numbers can't start with "$"
String Objects
• Creating a string object:
var myString = new String(“characters”)
var myString = “fred”
66
String functions
• indexOf () : returns the position of the first occurrence of a specified string
value in a string.
index values start their count with 0.
If no match occurs within the main string, the returned value is -1.
string.indexOf( searchString [, startIndex])
• toLowerCase() / toUpperCase()
Eg: var str="Hello World!";
str.toLowerCase() //returns hello world
str.toUpperCase() //returns HELLO WORLD
• slice( startIndex [, endIndex])
Extracts a part of a string and returns the extracted part in a new string
String functions
• split(“delimiterCharacter”[, limitInteger]) - Splits a string into array of strings
string.split(“delimiterCharacter”[, limitInteger])
Output :
var str = "zero one two three four"; zero
var arr = str.split(" ");
one
for(i = 0; i < str.length; i++){ document.write(“<br>” + arr[i]); }
two
var myString = “Anderson,Smith,Johnson,Washington” three
var myArray = myString.split(“,”) four
var itemCount = myArray.length // result: 4
68
Date
• Date object allows the handling of date and time information.
All dates are in milliseconds from January 1, 1970, 00:00:00.
Dates before 1970 are invalid dates.
• There are different ways to define a new instance of the date object:
var d = new Date() //Current date
var d = new Date(milliseconds)
var d = new Date(dateString)
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds)
<script>
var d=new Date();
document.write(d);
</script>
70
Array
• An array is data structure for storing and manipulating ordered collections of
data.
• An array can be created in several ways.
Eg1: Regular: ----------------------------------------- var cars=new Array();
Eg 2: Condensed: cars[0]="Spark";
o var cars=new Array("Spark","Volvo","BMW");
cars[1]="Volvo";
cars[2]="BMW";
Eg 3: Literal:
o var cars=["Spark","Volvo","BMW"];
Eg 4: var matrix = [[1,2,3], [4,5,6], [7,8,9]];
Eg 5 : var sparseArray = [1,,,,5];
• Deleting an array element eliminates the index from the list of accessible index
values
delete is a unary operator that attempts to delete myArray.length// result: 5
the object property or array element specified delete myArray[2]
myArray.length// result: 5
This does not reduce array’s length
myArray[2] // result: undefined
71
arrayObject.concat(array2)
var arrayText = myArray.join(“,”)
var a1 = new Array(1,2,3)
var a2 = new Array(“a”,”b”,”c”)
var a3 = a1.concat(a2)
// result: array with values 1,2,3,”a”,”b”,”c”
Example:
obj.methodName = function_name
obj.methodName(params)
76
• window.open(URL,name,specs)
URL : Specifies the URL of the page to open. If no URL is specified, a new window
with about:blank is opened
Name : Specifies the target attribute or the name of the window.
Specs : comma-separated list of items.
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>"); example opens an
myWindow.focus(); about:blank page in a new
browser window:
77
Document Object
When an HTML document is loaded into a web browser, it becomes a document
object; root node of the HTML document and owns all other nodes
Examples : Modifying content
Form validation
Example
Example
Example
<SCRIPT>
function valSelected(){
var radio = document.getElementsByClassName("r1");
for(var i = 0; i < radio.length; i++){
if(radio[i].checked) console.log("coffee selected : " + radio[i].value);
}
var checklist = document.getElementsByClassName("c1");
for(i=0;i<checklist.length;i++){
if (checklist[i].checked == true) console.log("Music selected : " + checklist[i].value);
}
</SCRIPT>
<FORM NAME="selectForm">
<B>Which Music types do you like?</B>
<input type="checkbox" class="c1" id="c1" value="blues">Blues</input>
<input type="checkbox" class="c1" id="c2" value="classical">Classical</input>
<input type="checkbox" class="c1" id="c3" value="opera">Opera</input>
<b>Choose Coffee to go with your music!</b><br>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="cappuchino">Cappuchino </input>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="latte">Latte</input>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="Mocha">Mocha</input>
<INPUT TYPE="button" VALUE="Which option selected?" onClick="valSelected()">
</FORM>
Regular Expressions
• A regular expression is an object that describes a pattern of characters.
Its matched against a text string, when you perform searches & replacements
Perform client-side data validations or any other extensive text entry parsing
RegExp objects may be created either with the RegExp() constructor or using a special
literal syntax.
regular expression literals are specified as characters within a pair of slash (/)
var
Eg
re = /web/gi expression is both case-insensitive and global
• \B Word Non-Boundary:
Get a match when it is not at the beginning or end of a word in the string
o /\Bor/ matches “normal” but not “origami”
o /or\B/ matches “normal” and “origami” but not “traitor”
o /\Bor\B/ matches “normal” but not “origami” or “traitor”
• [^…] Negated Character Set: any character not in the specified character set
o /[^AN]BC/ matches “BBC” and “CBC” but not “ABC” or “NBC”
• Positional Metacharacters
• “^” - At the beginning of a string or line
o /^Fred/ matches “Fred is OK” but not “I’m with Fred” or “Is Fred here?”
• “$” - At the end of a string or line
o /Fred$/ matches “I’m with Fred” but not “Fred is OK” or “Is Fred here?”
Method Description
executes a search for a match in a string. It returns an array of information or null
exec() on a mismatch.
test() tests for a match in a string. It returns true or false
executes a search for a match in a string. It returns an array of information or null
match() on a mismatch.
search() tests for a match in a string; returns the index of the match, or -1 if search fails
executes a search for a match in a string, and replaces the matched substring with
replace() a replacement substring.
split() uses a reg exp or a fixed string to break a string into an array of substrings.
When there’s a "g" flag, then str.match returns an array of all matches. There are no
additional properties in that array, and parentheses do not create any elements.
With no “g” flag, looks for the first match only.
Demo
What is Ajax ?
• “Asynchronous JavaScript And XML”
AJAX is not a programming language, but a technique for making the user
interfaces of web applications more responsive and interactive
It provide a simple and standard means for a web page to communicate with the
server without a complete page refresh.
Why Ajax?
• Intuitive and natural user interaction
• No clicking required. Call can be triggered on any event
• Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and refresh" user interaction
model
• Only user interface elements that contain new information are updated (fast
response)
• The rest of the user interface remains displayed as it is without interruption
(no loss of operational context)
XMLHttpRequest
• JavaScript object - XMLHttpRequest object for asynchronously exchanging the
XML data between the client and the server
• XMLHttpRequest Methods
open(“method”, “URL”, syn/asyn) : Assigns destination URL, method, mode
send(content) : Sends request including string or DOM object data
abort() : Terminates current request
getAllResponseHeaders() : Returns headers (labels + values) as a string
getResponseHeader(“header”) : Returns value of a given header
setRequestHeader(“label”,”value”) : Sets Request Headers before sending
• XMLHttpRequest Properties
Onreadystatechange : Event handler that fires at each state change
readyState values – current status of request
Status : HTTP Status returned from server: 200 = OK
responseText : get the response data as a string
responseXML : get the response data as XML data
Creating an AJAX application
• Step 1: Get an instance of XHR object
xhr.open("POST", "AddNos.jsp");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("tno1=100&tno2=200");
httpRequest.onreadystatechange = function(){
// process the server response
};
Ajax Demo
AJAX Demo with XML
Software
• Why jQuery
JavaScript is great for a lot of things especially manipulating the DOM but it’s pretty
complex stuff. DOM manipulation is by no means straightforward at the base level,
and that’s where jQuery comes in. It abstracts away a lot of the complexity involved in
dealing with the DOM, and makes creating effects super easy.
It can locate elements with a specific class
It can apply styles to multiple elements
It solves the cross browser issues
It supports method chaining
It makes the client side development very easy
<html>
<head>
<title>Test jQuery</title>
<script type="text/javascript" src="jquery-3.5.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('Hi');
});
</script>
</head>
<body>
Welcome to jQuery
</body>
</html>
$(function() {
// jQuery code
});
Introduction to selectors
• jQuery uses same CSS selectors used to style html page to manipulate elements
CSS selectors select elements to add style to those elements where as jQuery selectors
select elements to add behavior to those elements.
Selectors allow page elements (Single or Multiple) to be selected.
• Selector Syntax
$(selectorExpression)
jQuery(selectorExpression)
$(selector).action()
Selectors
• Selecting by Tag Name:
• Selecting single tag takes the following syntax
$(‘p’) – selects all <p> elements
$(‘a’) – selects all <a> elements
• To reference multiple tags, use the ( , ) to separate the elements
$(‘p, a, span’) - selects all paragraphs, anchors and span elements
• Selecting Descendants
• $(‘ancestor descendant’) - selects all the descendants of the ansector
$(‘table tr’) - Selects all tr elements that are the descendants of the table element
• Descendants can be children, grand children etc of the designated ancestor
element.
Demo
Selecting by Element ID
• It is used to locate the DOM element very fast.
• Use the # character to select elements by ID
$("#first") — selects the element with id="first"
$(‘#myID’) – selects the element with id=" myID "
• The index-related selectors (:eq(), :lt(), :gt(), :even, :odd) filter the set of elements
that have matched the expressions that precede them.
They narrow the set down based on the order of the elements within this matched set.
Eg, if elements are first selected with a class selector (.myclass) and four elements are
returned, these elements are given indices 0 through 3
• eq() - Select the element at index n within the matched set.
Eg : $("p:eq(1)") - Select the second <p> element
Eg : $("element:eq(0)") is same as $(‘element:first-child’)
• :gt() and lt() - Select all elements at an index > or < index within the matched set
Eg : $("tr:gt(3)") : Select all <tr> elements after the 4 first
Eg : $("tr:lt(4)") : Select the 4 first <tr> elements
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
<script>
$( "td:eq( 2 )" ).css( "color", "red" );
//$( "tr:first" ).css( "font-style", "italic" ); //is same as below line
$( "tr:eq(0)" ).css( "font-style", "italic" );
$( "td:gt(4)" ).css( "backgroundColor", "yellow" );
</script>
<script type="text/javascript">
$(document).ready(function() {
$('tr:odd').css('background-color','tomato');
$('tr:even').css('background-color','bisque');
});
</script>
<table border=1 cellspacing=5 cellpadding=5>
<th>column 1<th>column 2<th>column 3
<tr><td>data 1</td><td>data 2</td><td>data 3
<tr><td>data 4<td>data 5<td>data 6
<tr><td>data 7<td>data 8<td>data 9
<tr><td>data 10<td>data 11<td>data 12
</table>
Child Filter
• $(‘element:first-child’) and $(‘element:last-child’) selects the first child & last child
of its parent.
$(‘span:first-child’) returns the span which is a first child for all the groups
• :nth-child() - Selects all elements that are the nth-child of their parent. 1-based
indexing
Eg : $("p:nth-child(3)") - Select each <p> element that is the third child of its parent
Content Filters
• :contains() will select elements that match the contents.
$(‘div:contains(“hello”)’) - selects div’s which contains the text hello (match is case
sensitive)
• :empty - Select all elements that have no children (incl text nodes)
• :has : Selects elements which contain at least one element that matches the
specified selector.
Eg : $("p:has(span)") - Select all <p> elements that have a <span> element inside of
them
Eg : $("div:has(p,span,li)").css("border","solid red"); - Select all <div> elements that have
at least one of the given elements inside
• :parent - Select all elements that have at least one child node (either an element
or text).
Eg : $("td:parent") - Select all <td> elements with children, including text
jQuery Traversing -> filtering
• .eq() - Reduce the set of matched elements to the one at the specified index.
Eg : $("p").eq(1).css("background-color","yellow") - Select the second <p> element (index
number 1)
• .filter() - Reduce the set of matched elements to those that match the selector or
pass the function's test
Eg : $("p").filter(".intro") - Return all <p> elements with class "intro“
• .first() / last()
Eg : $("div p").first() - Select first <p> element inside first <div> element
• .has() - Reduce the set of matched elements to those that have a descendant that
matches the selector or DOM element.
Eg : $("p").has("span") - Return all <p> elements that have <span> element inside
jQuery Traversing -> Tree Traversal
• Instead of doing that and running $(“div”) three times, you could do this:
$("div").fadeOut().css("color", "red").text("hello world");
Getting Content
$.html() treats the string as HTML, $.text() treats the content as text
Getting Content
mouseup()
mouseover()
keydown()
keypress()
hover() : hover() method takes two functions
and is a combination of the mouseenter() $("#p1").hover(function(){
and mouseleave() methods. alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
Handling Click Events
• .click(handler([eventObject])) is used to listen for a click event or trigger a click
event on an element
$(‘#submitButton’).click(function() { alert(‘Clicked’) });
Using on() and off()
• The on() method attaches one or more event handlers for the selected elements.
$("#flip").click(function(){
$("#panel").slideDown();
});
$('.blueDiv').fadeTo(1000,0.1,function(){
$('#results').text('FadeTo Animation Completed');
});
Creating Custom Animation
• Custom animation can be created in jQuery with the animate() function
animate(params, duration, callback)
o params contains the properties of the object you’re animating, such as CSS properties, duration is
the optional time in milliseconds that the animation should take and callback is an optional
callback function.
<style type="text/css">
#content { background-color:#ffaa00; width:300px; height:30px; padding:3px; }
</style>
<script type="text/javascript">
$(document).ready(function() {
$("#animate").click(function() {
$("#content").animate({"height": "100px", "width": "350px"}, "slow");
});
});
</script>
</head>
<body>
<input type="button" id="animate" value="Animate"/>
<div id="content">Animate Height</div> </body>
$.get('GetContents.html',function(data){
$('#targetDiv').html(data);
},'html');
$.getJSON('GetContents.aspx,{id:5},function(data){
$('#targetDiv').html(data);
});
$.ajax({
url: “employee.asmx/GetEmployees",
data : null,
contentType: "application/json; charset=utf-8",
datatype: ‘json’,
success: function(data,status,xhr){
//Perform success operation
},
error: function(xhr,status,error) {
//show error details
}
});
NODE.JS
Server Side Javascript
Node.js – an intro
• In 2009 Ryan Dahl created Node.js or Node, a framework primarily used to create highly
scalable servers for web applications.
Node.js is an open source, cross-platform runtime environment for server-side JavaScript.
Node.js is required to run JavaScript without a browser support. It uses Google V8 JavaScript engine to
execute code.
It is written in C++ and JavaScript.
Node.js is a development framework that is based on Google’s V8 JavaScript engine that powers
Google's Chrome web browser.
You write Node.js code in JavaScript, and then V8 compiles it into machine code to be executed.
It’s a highly scalable system that uses asynchronous, non-blocking I/O model (input/output), rather than
threads or separate processes
It is not a framework like jQuery nor a programming language like C# or JAVA; Its primarily a Javascript
engine
• This style of programming — whereby instead of using a return value you define functions
that are called by the system when interesting events occur — is called event-driven or
asynchronous programming.
Typical blocking I/O
programming
result = query('SELECT * FROM posts WHERE id = 1');
do_something_with(result);
query_finished = function(result) {
do_something_with(result);
}
query('SELECT * FROM posts WHERE id = 1', query_finished);
Event loop
• An event loop is a construct that mainly performs two functions in a continuous loop —
event detection and event handler triggering.
In any run of the loop, it has to detect which events just happened.
Then, when an event happens, the event loop must determine the event callback and invoke it.
• This event loop is just one thread running inside one process, which means that, when
an event happens, the event handler can run without interruption. This means the
following:
There is at most one event handler running at any given time.
Any event handler will run to completion without being interrupted.
Node.js uses the “Single Threaded Event Loop” architecture to handle multiple concurrent clients.
• Node.js is not fit for an application which performs CPU-intensive operations like image
processing or other heavy computation work because it takes time to process a request
and thereby blocks the single thread.
• Node.js is great for data-intensive applications.
Using a single thread means that Node.js has an extremely low-memory footprint when used as
a web server and can potentially serve a lot more requests.
Eg, a data intensive application that serves a dataset from a database to clients via HTTP
//helloworld.js
console.log("Hello World!");
Using the REPL
• To view the options available to you in REPL type .help and press Enter.
Node js Modules
• A module in Node.js is a logical encapsulation of code in a single unit.
Since each module is an independent entity with its own encapsulated functionality, it can be managed
as a separate unit of work.
• Node.js has a set of built-in modules which you can use without any further installation.
Built-in modules provide a core set of features we can build upon.
Also, each module can be placed in a separate .js file under a separate folder.
To include a module, use the require() function with the name of the module.
res.end(body);
}
Node.js Module
• Node.js includes three types of modules:
Core Modules
Local Modules
Third Party Modules
exports object is a special object created by the Node module system which is returned as the value of
the require function when you include that module.
• Exports is just module.exports’s little helper. Your module returns module.exports to the caller ultimately,
not exports. All exports does is collect properties and attach them to module.exports
//module7.js //import the assigned properties with a destructuring assignment:
function sayHello(){ const { username, sayHello } = require(‘./module7’)
console.log("Hello World!")
} //Or with a regular assignment and dot notation:
//alternatively
exports.username = username
exports.sayHello = sayHello
• There are two ways to install a package using npm: globally and locally.
• Globally − This method is generally used to install development tools and CLI based
packages. To install a package globally, use the following code.
npm install -g <package-name>
Eg to install expressJS : npm install -g express
Eg to install Typescript : npm install –g typescript
Eg to install Angular : npm install -g @angular/cli
• Locally − This method is generally used to install frameworks and libraries. A locally
installed package can be used only within the directory it is installed.
To install a package locally, use the same command as above without the -g flag.
npm install <package-name>
Eg : To install cookie parser in Express : npm install --save cookie-parser
Eg: to install bootstrap : npm install [email protected]
• Installing a package using NPM : $ npm install [g] <Package Unique Name>
• To remove an installed package : npm uninstall [g] < Package Unique Name>
• To update a package to its latest version : npm update [g] < Package Unique Name>
Loading a third party module : package.json
• The package.json file in Node.js is the heart of the entire application.
It is basically the manifest file that contains the metadata of the project.
package.json is a configuration file from where the npm can recognize dependencies between packages
and installs modules accordingly.
It must be located in project’s root directory.
It contains human-readable metadata about the project (like the project name and description) as well as
functional metadata like the package version number and a list of dependencies required by the
application.
Your project also must include a package.json before any packages can be installed from NPM.
Eg : a minimal package.json:
{
"name" : "barebones",
"version" : "0.0.0",
}
o The name field should explain itself: this is the name of your project. The version field is used by npm to make sure
the right version of the package is being installed.
See how package.json is installed in root folder along with node_modules folder
My Express app is dependent on a number of other modules
All these dependencies will have an entry in package.json
Loading a file module
• Loading a file module (User defined module)
We load non-core modules by providing the absolute path / relative path.
Node will automatically add the .js extension to the module referred.
var myModule = require(‘d:/shrilata/nodejs/module'); // Absolute path for module.js
var myModule = require('../module'); // Relative path for module.js (one folder up level)
var myModule = require('./module'); // Relative path for module.js (Exists in current directory)
If the given path does not exist, require() will throw an Error with its code property set to
'MODULE_NOT_FOUND'.
package.json
• The package.json file in Node.js is the heart of the entire application.
• It is basically the manifest file that contains the metadata of the project.
• package.json is a configuration file from where the npm can recognize dependencies
between packages and installs modules accordingly.
It must be located in project’s root directory.
• package-lock.json file
Introduced in version 5; keeps track of the exact version of every package that is installed so that
a product is 100% reproducible in the same way even if packages are updated by their
maintainers.
The package-lock.json sets your currently installed version of each package in stone, and npm
will use those exact versions when running npm install.
Buffers
• A buffer is an area of memory; It represents a fixed-size chunk of memory (can't be resized)
allocated outside of the V8 JavaScript engine.
You can think of a buffer like an array of integers, which each represent a byte of data.
It is implemented by the Node.js Buffer class.
• Creating Buffer
It is possible to create your own buffer! Aside from the one Node.js will automatically create during a
stream, it is possible to create and manipulate your own buffer
A buffer is created using the : Buffer.alloc(), Buffer.allocUnsafe() , Buffer.from()
Eg : Create a buffer of length 20, with initializing all the value to fill as 0 in hexadecimal format
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to
handle exceptions or allow them to bubble up.
Asynchronous method is preferred over synchronous method because it never blocks the program
execution where as the synchronous method blocks.
Node.js File System
• Node fs module provides an API to interact with FileSystem and to perform some IO
operations like create a file, read a File, delete a File etc..
fs module is responsible for all the async or synchronous file I/O operations.
var fs = require("fs");
var path = "/";
fs.exists(path, function(exists) {
if (exists)
console.log(path + " exists: " + exists);
else
console.error("Something is wrong!");
});
• Reading Directories
We can use the fs.readdir() method to list all the files const fs = require('fs')
and directories within a specified path: fs.readdir('./', (err, files) => {
if (err) {
console.error(err)
return
}
console.log('files: ', files)
})
• fs.write(fd, string[, position[, encoding]], callback): write into an opened file; specified by fd
• Alternatively :fs.write(fd, buffer[, offset[, length[, position]]], callback)
var s = http.createServer(process_request);
s.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Web development with Node : http.ServerRequest
• When listening for request events, the callback gets an http.ServerRequest object as the
first argument (function(req,res))
• This object contains some properties:
req.url: This property contains the requested URL as a string
o It does not contain the schema, hostname, or port, but it contains everything after that.
o Eg : if URL is :http://localhost:3000/about?a=20 then req.url will return /about?a=20
req.method: This contains the HTTP method used on the request. It can be, for example, GET,
POST, DELETE, or HEAD.
req.headers: This contains an object with a property for every HTTP header on the request.
Eg : Serving file on request : Reading a file at server end and serving to browser!
<html>
var http = require('http'); <body>
var url = require('url'); <h1>Login</h1>
var fs = require('fs'); <form action="process">
Radius : <input name="radius">
function process_req(req, res) { <input type="submit"
if (req.method == 'GET' && req.url == '/') { value="Calc Radius">
fs.readFile('radius.html', function(err, data) { </form>
res.writeHead(200, {'Content-Type': 'text/html'}); </body></html>
res.write(data);
res.end();
});
}
else if(req.method == 'GET' && req.url.substring(0,8) == '/process'){
var q = url.parse(req.url, true);
var qdata = q.query;
var r = qdata.radius;
{ radius: '100' }
var rad = Math.PI + r * r;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The area is : " + rad);
res.end();
}
else
res.end("not found");
}
var server = http.createServer(process_req)
server.listen(3000);
console.log('server listening on localhost:3000');
<body> //loginpost.html
var http = require('http'); <h1>Login</h1>
var fs = require('fs'); <form action="processlogin"
method="post">
function process_req(req, res) { Username :
if (req.method == 'GET' && req.url == '/') { <input name="uname"><br>
fs.readFile('loginPost.html', function(err, data) { Password :
res.writeHead(200, {'Content-Type': 'text/html'}); <input type="password"
res.write(data); name="passwd"><br>
res.end(); <input type="submit"
}); value="login">
} </form>
else if(req.method == 'POST'){ </body>
var body = "";
req.on("data",function(data){
body += data;
res.writeHead(200, {'Content-Type': 'text/html'});
var arr = body.split("&");
res.write("Welcome " + arr);
res.end();
})
}
}
var server = http.createServer(process_req)
server.listen(3000);
console.log('server listening on localhost:3000');
Promise
• Promises are a new feature of ES6.
It’s a method to write asynchronous code; it represents the completion of an asynchronous function.
It is a Javascript object that might return a value in the future.
It accomplishes the same basic goal as a callback function, but with many additional features and a
more readable syntax.
• Creating a Promise
Promises are created by using a constructor called Promise and passing it a function that receives two
parameters, resolve and reject, which allow us to indicate to it that it was resolved or rejected.
Example promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
promise.then(function(result) {
console.log("Promise worked");
}, function(err) {
console.log("Something broke");
});
Consuming a Promise
Full example
setTimeout(
() => number > expected
? resolve(number)
: reject(new Error('lower than expected number')), 1000
);
});
}
randomDelayed(100, 75, 2500)
.then(number => console.log(number))
.catch(error => console.error(error.toString()));
Chained Promises
• The methods promise.then(), promise.catch(), and promise.finally() can be used to associate
further action with a promise that becomes settled.
Each .then() returns a newly generated promise object, which can optionally be used for chaining
function load(url) {
return new Promise(function (resolve, reject) {
const request = new XMLHttpRequest();
request.onreadystatechange = function (e) {
if (this.readyState === 4) {
if (this.status == 200) {
resolve(this.response);
} else {
reject(this.status);
btn.onclick = function () {
}
load('data.json')
}
.then(
}
response => {
request.open('GET', url, true);
const result = JSON.parse(response);
request.send();
$(“#msg”).text(result.message);
});
},
}
error => $(“#msg”).text(`Error getting message,
HTTP status: ${error}`
);
}
Using Fetch
• One of the most useful and frequently used Web APIs that returns a promise is the
Fetch API.
It allows you to make an asynchronous resource request over a network.
fetch() is a two-part process, and therefore requires chaining then()
async/await
• To consume the value returned when the promise fulfills (since it is returning a promise) use a
.then() block
//complete example
async function hello(){
return "hello-1"
}
hello().then((x)=>console.log(x))
// returns"hello-1"
f().then(function(result) {
console.log(result)
});
The await keyword
• The await keyword is used inside the async function to wait for the asynchronous operation
await can be put in front of any async promise-based function to pause your code on that line until the
promise fulfills, then return the resulting value.
Syntax: let result = await promise;
You can use await when calling any function that returns a Promise, including web API functions
// a promise
let promise = new Promise(function (resolve, reject) { function logFetch(url) {
setTimeout(function () { return fetch(url)
resolve('Promise resolved')}, 4000); .then(response => response.text())
}); .then(text => {
console.log(text);
}).catch(err => {
async function asyncFunc() {// async function console.error('fetch failed', err);
});
// wait until the promise resolves }
let result = await promise;
async function logFetch(url) {
console.log(result); try {
console.log('hello'); const response = await fetch(url);
} console.log(await response.text());
}
asyncFunc(); // calling the async function catch (err) {
console.log('fetch failed', err);
}
}
constructor method is
always defined with
the name "constructor"
console.log(square.calcArea()); // 100
Next gen Javascript : Spread and rest operators
• spread:
// Destructuring assignment
var {x, y, width, height} = rect;
console.log(x, y, width, height); // 0,10,15,20
rect.x = 10;
const arr=[1,2,3,4,5]
var [a,b] = arr
console.log(a,b) //1,2
Array functions
• Array.filter
You can filter arrays by using the .filter(callback) method.
The result will be another array that contains 0 or more elements based on the condition (or the
"check") that you have in the callback.
Array functions
• Array.map() : returns a new array containing the result of invoking the callback
function for every item in the array.
• With a template, we can create one string and insert the variable values by surrounding
them with ${variable}.
console.log(`${lastName}, ${firstName} ${middleName}`)
Any JavaScript that returns a value can be added to a template string between the ${ } in a
template string.
//Javascript : generating an html string
var msg1 = 'Have a great day';
var html = '<div>' + msg1 + '</div>';
document.write(html)
Introduction
• Bootstrap is an opensource frontend framework developed by Twitter.
It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first
web sites.
Bootstrap is a free and open source collection of tools for creating websites and web applications.
Bootstrap contains a set of CSS- and HTML-based templates for styling forms, elements, buttons,
navigation, typography, and a range of other UI components.
It also comes with optional JavaScript plugins to add interactivity to components.
• Responsive web design is about creating web sites which automatically adjust themselves
to look good on all devices, from small phones to large desktops.
Developers can then create a single design that works on any kind of device: mobiles, tablets, smart
TVs, and PCs
Where to Get Bootstrap 4?
• There are two ways to start using Bootstrap 4 on your own web site.
Download Bootstrap 4 from getbootstrap.com : https://getbootstrap.com/docs/4.5/getting-
started/download/
If you don't want to download and host Bootstrap 4 yourself, you can include it from a CDN (Content
Delivery Network).
MaxCDN provides CDN support for Bootstrap's CSS and JavaScript. You must also include jQuery
The https://getbootstrap.com/docs/4.5/getting-started/introduction/ page gives CDN links for CSS and
js files
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 4 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">
</script>
</head>
<body>
//body comes here
</body>
</html>
To ensure proper rendering and touch zooming, add this <meta> tag
• The width=device-width part sets the width of the page to follow the
screen-width of the device (which will vary depending on the device).
• The initial-scale=1 part sets the initial zoom level when the page is first
loaded by the browser.
Create First Web Page With Bootstrap 4
• Bootstrap 4 also requires a containing element to wrap site contents.
• There are two container classes to choose from:
The .container class provides a responsive fixed width container
The .container-fluid class provides a full width container, spanning the entire width of the
viewport
Bootstrap Container
• Bootstrap container is basically used in order to create a centered area that lies within the
page and generally deals with the margin of the content and the behaviors that are
responsible for the layout.
It contains the grid system (row elements, which in turn are the container of columns).
• There are two container classes in Bootstrap:
.container: provides a fixed width container with responsiveness. It will not take the complete width of
its viewport.
.container-fluid: provides a full width container of the viewport and its width will change (expand or
shrink) on different screen sizes.
<body>
<div class="container">
<h1>Container</h1>
</div>
</body>
Bootstrap Grid System
• Bootstrap grid system divides the screen into columns―up to 12 in each row. (rows are
infinite)
The column widths vary according to the size of screen they're displayed in.
Bootstrap's grid system is responsive, as the columns resize themselves dynamically when the
size of browser window changes.
If you do not want to use all 12 columns individually, you can group the columns together to
create wider columns
it is a good practice to wrap all the contents within a container; create a row (with class row)
inside a container, then start creating the columns.
<div class="container">
<div class="row">
//add desired number of cols here
</div>
</div>
Grid Classes
• The Bootstrap 4 grid system has five classes:
.col- (extra small devices - screen width less than 576px)
.col-sm- (small devices - screen width equal to or greater than 576px)
.col-md- (medium devices - screen width equal to or greater than 768px)
.col-lg- (large devices - screen width equal to or greater than 992px)
.col-xl- (xlarge devices - screen width equal to or greater than 1200px)
Example
Building a Basic Grid
MISC COMPONENTS
<h1> - <h6>
• Typography refers to the various styles present in Bootstrap style sheets which define how
various text elements will appear on the web page.
HTML uses default font and style to create headings, paragraphs, lists and other inline elements.
Bootstrap overrides default and provides consistent styling across browsers for common typographic
elements.
• Bootstrap 4 styles HTML headings (<h1> to <h6>) with a bolder font-weight and an increased
font-size
• Additionally, you can use the <small> tag with .text-muted class to display the secondary text
of any heading in a smaller and lighter variation.
• Text Coloring
Colors are the powerful method of conveying important information in website design.
Tables
• Bootstrap provides an efficient layout to build elegant tables
You can create tables with basic styling that has horizontal dividers and small cell padding, by just adding
the Bootstrap's class .table to the <table> element.
Jumbotron
• A jumbotron indicates a big box for calling extra attention to some special content or
information.
A jumbotron is displayed as a grey box with rounded corners. It also enlarges the font sizes of
the text inside it.
Just wrap your featured content like heading, descriptions etc. in a <div> element and apply the
class .jumbotron on it.
Tip: Inside a jumbotron you can put nearly any valid HTML, including other Bootstrap
elements/classes.
<div class="jumbotron">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS, and JS framework for
developing responsive, mobile-first projects on the web.</p>
</div>
images
• To add images on the webpage use element <img> , it has three classes to apply
simple styles to images.
.img-rounded : To add rounded corners around the edges of the image, radius of the border is
6px.
.img-circle : To create a circle of radius is 500px
.img-thumbnail : To add some padding with grey border , making the image look like a polaroid
photo.
Bootstrap 4 Icons
• Bootstrap 4 does not have its own icon library; but there are many free icon libraries to
choose from, such as Font Awesome and Google Material Design Icons
To use Font Awesome icons, add the following CDN link to your HTML page
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-
UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous">
<i class="fas fa-cloud"></i>
<i class="fas fa-coffee"></i>
<i class="fas fa-car"></i>
<i class="fas fa-file"></i>
<i class="fas fa-bars"></i>
Alerts
• Bootstrap comes with a very useful component for displaying alert messages in various
sections of our website
You can use them for displaying a success message, a warning message, a failure message, or an
information message.
These messages can be annoying to visitors, hence they should have dismiss functionality added to
give visitors the ability to hide them.
Bootstrap Lists
• Unstyled Ordered and Unordered Lists
Sometimes you might need to remove the default styling form the list items. You can do this by simply
applying the class .list-unstyled to the respective <ul> or <ol> elements
• If you want to create a horizontal menu using ordered or unordered list you need to place all
list items in a single line i.e. side by side.
You can do this by simply applying the class .list-inline to the respective <ul> or <ol>, and the class .list-
inline-item to the <li> elements.
Page Components : List Group
• List group is used for creating lists; eg a list of useful resources or a list of recent activities
Add class list-group to a <ul> or <div> element to make its children appear as a list.
The children can be li or a element, depending on your parent element choice.
The child should always have the class list-group-item.
• We can also apply various colors to each list item by adding list-group-item-*
classes along with list-group-item.
Bootstrap 4 Navs
• Navs : a group of links placed inline with each other to be used for navigation.
There are options to make this group of links appear either as tabs or small buttons, the latter known
as pills in Bootstrap.
If you want to create a simple horizontal menu, add the .nav class to a <ul> element, followed by
.nav-item for each <li> and add the .nav-link class to their links:
Add the class .nav-tabs to the basic nav to generate a tabbed navigation.
Similarly, you can create pill based navigation by adding the class .nav-pills on the basic nav instead
of class .nav-tabs
Vertically stack these pills by attaching an additional class flex-column
Navbar
• A navbar is a navigation header that is placed at the top of the page
A standard navigation bar is created with the .navbar class, followed by a responsive collapsing class:
.navbar-expand-xl|lg|md|sm
To add links inside the navbar, use a <ul> element with class="navbar-nav".
Then add <li> elements with a .nav-item class followed by an <a> element with a .nav-link class
Navbar
Standing Out : Buttons
• Its easy to convert an a, button, or input element into a fancy bold button in Bootstrap; just
have to add the btn class
You can also create outline buttons by replacing the button modifier classes
<form class="form">
<div class="form-group">
<label for=“n1">Name</label>
<input type="text" class="form-control" id=“n1“ placeholder="Your Name" />
</div>
</form>
class form-control in an
input element will make it a
full-width element
Introduction
• If you write serious apps using only core Node.js modules you most likely find
yourself reinventing the wheel by writing the same code continually for similar
tasks, such as the following:
Parsing of HTTP request bodies and Parsing of cookies
Managing sessions
Organizing routes with a chain of if conditions based on URL paths and HTTP methods of
the requests
Determining proper response headers based on data types
{
"name": "express-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
First app
• An Express app is created by calling the express() function
express() : Creates an Express application; is a top-level function exported by the
express module
The app object conventionally denotes the Express application.
This object, which is traditionally named app, has methods for routing HTTP requests,
configuring middleware, rendering HTML views, registering a template engine, and
modifying application settings that control how the application behaves
app.get("/",function(req,resp){
resp.send("Hello world")
})
app.listen(3000, function(){
console.log("app running on port 3000")
})
http.createServer(app).listen(8000);
Express Routes
• If none of your routes match the request, you'll get a "Cannot GET <your-
request-route>" message as response.
• This message can be replaced by a 404 not found page using this simple route
Routing basics
app.get("/", function(req, res, next) {
res.send("Hello <strong>home page</strong>");
});
• Express also augments the request and response objects with additional
methods. Example response.send() .
send() is used to send a response status code and/or body back to the client.
If the first argument to send() is a number, then it is treated as the status code. If a
status code is not provided, Express will send back a 200.
The response body can be specified in the first or second argument, and can be a string,
Buffer, array, or object.
Route Parameters
• Route can be parameterized using a regular expression
/products?productId=sweater
/products/sweater
Doesn’t match:
/products/books/aaa
/products/books//
/products//
Eg 2 : Using regular expressions to match routes
Assume you want to match things like /users/123 or /users/456 but not /users/anita. You
can code this into a regular expression and also grab the number
• req.params - An object containing parameter values parsed from the URL path.
For example, if you have the route /user/:name, then the “name” property is available
as req.params.name. This object defaults to {}.
GET /user/shrilata
req.params.name // => “shrilata“
When you use a regular expression for the route definition, each capture group match
from the regex is available as req.params[0], req.params[1]
GET /file/javascripts/jquery.js
req.params[0] // => "javascripts/jquery.js"
Route Parameters
• One of the most powerful features of routing is the ability to use placeholders to
extract named values from the requested route, marked by the colon ( :)
character.
When the route is parsed, express puts the matched placeholders on the req.params
object for you.
app.listen(3000);
Handle POST Request
• To handle HTTP POST request in Express.js version 4 and above, you need
to install a middleware module called body-parser.
This is used to parse the body of requests which have payloads attached to them.
This body-parser module parses the JSON, buffer, string and url encoded data
submitted using HTTP POST request.
Eg :To parse json data: app.use(bodyParser.json())
The next() function gives you the opportunity to do some additional examinations on
the incoming URL and still choose to ignore it
app.get('/example/b', f1 , f2 , f3);
……..
function f1(){
//handle the callback
next();
}
Routing handlers
//More than one callback function can handle a route
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
• Using EJS:
1. install ejs : npm install ejs –save
2. Create a folder called “views” in main project folder
What is React?
• From the official React page : A JavaScript library for building user interfaces
• Its not a framework; React does only one thing – create awesome UI!
• React is used to build single page applications.
• React.js is a JavaScript library. It was developed by engineers at Facebook.
• React is a declarative, efficient, and flexible JavaScript library for building
user interfaces.
• It lets you compose complex UIs from small and isolated pieces of code
called “components”.
Client-side Javascript frameworks
• Ember : was initially released in December 2011. It is an older framework that has
less users than more modern alternatives such as React and Vue
• Angular is an open-source web application framework led by the Angular Team at
Google and by a community of individuals and corporations.
• Vue : first released in 2014; is the youngest of the big four, but has enjoyed a recent
uptick in popularity.
• React : released by Facebook in 2013. By this point, FB had already been using
React to solve many of its problems internally.
React itself is not technically a framework; it's a library for rendering UI components.
React is used in combination with other libraries to make applications — React and React
Native enable developers to make mobile applications; React and ReactDOM enable them
to make web applications, etc.
Components
• A Component is one of the core building blocks of React.
• Its just a custom HTML element!
• Every application you will develop in React will be made up of pieces called
components.
Components make the task of building UIs much easier. You can see a UI broken down
into multiple individual pieces called components and work on them independently and
merge them all in a parent component which will be your final UI.
Why react
• Created and maintained by facebook
• Has a huge community on Github
• Component based architecture
• React is fast. Apps made in React can handle complex updates and still feel
quick and responsive.
• React is modular. Instead of writing large, dense files of code, you can write
many smaller, reusable files. React’s modularity can be a beautiful solution to
JavaScript’s maintainability problems.
• React is scalable. Large programs that display a lot of changing data are
where React performs best.
• React is popular.
• UI state becomes difficult to manage with vanilla Javascript
Requirements
• Ensure that NodeJS and typescript are installed
Install TypeScript as follows:
npm install –g typescript
Using create-react app
• npx create-react-app my-app
• cd my-app
• npm start
function App() {
/*return (
<div >
<h2>Welcome to React!</h2>
</div>
);*/
return React.createElement('div',null,'h2','Hi, welcome to React');
}
export default App;
function App() {
/*return (
<div >
<h2>Welcome to React!</h2>
</div>
);*/
return React.createElement('div',null,
React.createElement('h1',{className:'App'},'Hi welcome to React'));
}
export default App;
Understanding JSX
• Eg : const mytag = <h1>Hello React!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));
const myelement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
ReactDOM.render(myelement, document.getElementById('root'));
const myelement = (
<div> If we want to return more
<h1>I am a Header.</h1> elements, we need to wrap
<h1>I am a Header too.</h1> it with one container
</div> element. Notice how we
); are using div as a wrapper
for the two h1 elements.
ReactDOM.render(myelement, document.getElementById('root'));
Creating a functional component
• Components are the essential building blocks of any app created with React
A single app most often consists of many components.
• A component is in essence, a piece of the UI - splitting the user interface into
reusable and independent parts, each of which can be processed separately.
Components are independent and reusable bits of code.
It’s an encapsulated piece of logic.
They serve the same purpose as JavaScript functions, but work in isolation and return
HTML via a render function.
function ExpenseItem(){
return <h2>Expense Item</h2>
}
export default ExpenseItem;
import "./ExpenseItem.css"
return (
<div className="expense-item">
<div>{expDate.toISOString()}</div>
<div className="expense-item__description"> Comments in JSX
<h2>{expTitle}</h2>
<p className="expense-item__price">Rs {expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;
Outputting dynamic content – another example
//Person.js Wrap dynamic
import React from 'react'; content in JSX in {...}
function App() {
return (
<div className="App">
<h1> Hi, welcome to React</h1>
<Person />
<Person />
<Person />
</div>
);
}
}
PROPS
Passing data via ‘Props’
• “Props” stands for properties.
It is a special keyword in React used for passing data from one component to another.
Props are arguments passed into React components.
props are read-only. So, the data coming from a parent component can't be changed by
the child component.
Props are passed to components via HTML attributes.
Props can be used to pass any kind of data such as: String, Array, Integer, Boolean,
Objects or, Functions
//Person.js
import React from 'react';
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpenseItem expDate={expenses[0].date} expTitle={expenses[0].title}
expAmount={expenses[0].amount}/>
<ExpenseItem expDate={expenses[1].date} expTitle={expenses[1].title}
expAmount={expenses[1].amount}/>
<ExpenseItem expDate={expenses[2].date} expTitle={expenses[2].title}
expAmount={expenses[2].amount}/>
</div>
);
}
export default App;
“Javascript” in components
const ExpenseItem = (props) => {
const month = props.expDate.toLocaleString('en-US', {month: 'long'});
const day = props.expDate.toLocaleString('en-US', {day: '2-digit'});
const year = props.expDate.getFullYear();
return (
<div className="expense-item">
<div>
<div>{month}</div>
<div>{day}</div>
<div>{year}</div>
</div>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;
import "./ExpenseDate.css"
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;
No parenthesis ()
STATEFUL COMPONENTS
React State
• The state is a built-in React object that is used to contain data or information
about the component.
• A component’s state can change over time; whenever it changes, the
component re-renders.
The change in state can happen as a response to user action or system-generated
events and these changes determine the behavior of the component and how it will
render.
• A component with state is known as stateful component.
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{title}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;
React Hooks
• Hooks allow us to "hook" into React features such as state and lifecycle methods
React Hooks are special functions provided by React to handle a specific functionality
inside a React functional component.
Eg React provides useState() function to manage state in a functional component.
When a React functional component uses React Hooks, React Hooks attach itself into
the component and provides additional functionality.
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{title}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;
//AllPosts //Post
const posts = () => { const post = (props) => {
return ( return (
<div> <div>
<Post title="My first Post" /> <h1>{props.title}</h1>
<Post title="My second Post" /> </div>
</div> );
); }
}
props and state
• State : While props allow you to pass data down the component tree (and hence
trigger an UI update), state is used to change the component’s, well, state from
within.
Changes to state also trigger an UI update.
Example: NewPost Component: this component contains state . Only class-based
components can define and use state . You can of course pass the state down to
functional components, but these then can't directly edit it.
class NewPost extends Component { // state can only be accessed in class-based components!
state = {
counter: 1
};
return(
<ChildComponent uname={uname} email={email} />
);
} function App() {
export default ParentComponent; return (
<div className="App">
<h2>Welcome to React!</h2>
const ChildComponent = (props) => { <ParentComponent />
return( ...
<div>
<div>Name : {props.uname}</div>
<div>Email : {props.email}</div>
</div>
);
}
export default ChildComponent;
Form submission
Form submission – extracting data, 2-way binding
const ExpenseForm = () => {
return (
<div className="App">
<h2>Welcome to React!</h2>
<NewExpense onAddExpense={addExpenseHandler} />
...
); const NewExpense = (props) => {
}
export default App; const saveExpenseDataHandler = (inputExpenseData) => {
const expenseData = {
...inputExpenseData,
id:Math.random().toString()
}
//console.log("In NewExpense ",expenseData)
props.onAddExpense(expenseData)
}
return(...);
}
export default NewExpense;
LIFTING STATE UP
Lifting state up in React.js
• In a typical application, you pass a lot of state down to child components as props.
These props are often passed down multiple component levels.
That's how state is shared vertically in your application.
• Often there will be a need to share state between different components.
The common approach to share state between two components is to move the state to
common parent of the two components.
This approach is called as lifting state up in React.js
React components can manage their own state
Often components need to communicate state to others
Siblings do not pass state to each other directly
State should pass through a parent, then trickle down
App
C1 C2
<div className='expenses-filter__control'>
<label>Filter by year</label>
<select onChange={selectChangeHandler}> ExpenseItem NewExpense ExpensesFilter
<option value='2022'>2022</option>
<option value='2021'>2021</option>
<option value='2020'>2020</option> ExpenseDate ExpenseForm
<option value='2019'>2019</option>
</select>
</div> function App() {
</div> const [filteredYear, setFilteredYear] = useState(2020);
);
}; const selectYearHandler = filteredValue => {
export default ExpensesFilter; setFilteredYear(filteredValue)
}
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpensesFilter onSelectYear={selectYearHandler}/>
return(...);
}
export default SimpleListChildComponent;
Working with the expenses list
const expenses = [
{ title: 'Groceries’, amount: 900, date: new Date(2020, 7, 14)},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'SofaSet', amount: 25000, date: new Date(2021, 2, 28)}
];
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpenseItem
expDate={expenses[0].date}
expTitle={expenses[0].title}
expAmount={expenses[0].amount}
/>
<ExpenseItem
expDate={expenses[1].date}
expTitle={expenses[1].title}
expAmount={expenses[1].amount}
/>
<ExpenseItem
expDate={expenses[2].date}
expTitle={expenses[2].title}
expAmount={expenses[2].amount}
/>
</div>
);
}
const DUMMY_EXP = [
{ id:101, title: 'Groceries', amount: 900, date: new Date(2020, 7, 14)},
{ id:102,title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ id:103,title: 'New Sofa Set', amount: 25000, date: new Date(2021, 2, 28)}
];
function App() {
<div>
{people.map(person => (
<p key={person.name}>{person.name}</p>
))}
</div>
Implementing filters
function App() {
const [expenses, setExpenses] = useState(DUMMY_EXP)
const [filteredYear, setFilteredYear] = useState(2020);
...
const selectYearHandler = filteredValue => {
setFilteredYear(filteredValue)
}
return (
<div className="App">
<h2>Welcome to React!</h2>
<NewExpense onAddExpense={addExpenseHandler} />
<ExpensesFilter onSelectYear={selectYearHandler}/>
{filteredExpensesArr.map(expense => (
<ExpenseItem
key={expense.id}
expDate={expense.date}
expTitle={expense.title}
expAmount={expense.amount}
/>))
}
Rendering content conditionally
• Conditional rendering means to render a specific HTML element or React
component depending on a prop or state value.
In a conditional render, a React component decides based on one or several conditions
which DOM elements it will return.
For instance, based on some logic it can either return a list of items or a text that says
"Sorry, the list is empty".
if(condition_is_met) {
renderSectionOfUI();
}
//ExpenseForm
<div className="new-expense__actions">
<button type="button"
onClick={props.onCancel}>Cancel</button>
<button type="submit">Add Expense</button>
</div>
CLASS-BASED COMPONENTS
const HelloComponent = (props) => {
Functional components are regular
return (<h3>Hello, welcome user!!</h3>)
javascript functions which return
}
renderable results (typically JSX)
export default HelloComponent;
import './User.css';
import React, {Component} from 'react';
LIFECYCLE EVENTS
Lifecycle Events
• React class components can have hooks for several lifecycle events
During the lifetime of a component, there’s a series of events that gets called, and to
each event you can hook and provide custom functionality.
React lifecycle methods are a series of events that happen from the birth of a React
component to its death.
There are 4 phases in a React component lifecycle:
o initial
o Mounting
o Updating
o Unmounting
Lifecycle methods
• React lifecycle methods:
Each React lifecycle phase has a number of lifecycle methods that you can override
to run code at specified times during the process.
These are popularly known as component lifecycle methods.
• Initialisation phase:
Constructor(props): This is a special function that is called when new components
are created. In this, we initialize the state or props of the component.
Lifecycle methods
• The mounting phase refers to the phase during which a component is created and
inserted to the DOM.
• The following methods are called in order.
ComponentWillMount(): This function is called immediately before mounting occurs. It
is called right before the first rendering is performed.
render(): You have this method for all the components created. It returns the Html node.
Lifecycle methods
• Update: In this state, the dom is interacted by a user and
updated. For example, you enter something in the textbox,
so the state properties are updated.
The component is re-rendered whenever a change is made to
react component’s state or props, you can simply say that the
component is updated.
• Following are the methods available in update state:
shouldComponentUpdate() : called when the component is
updated.
componentDidUpdate() : after the component is updated.
• UnMounting: this state comes into the picture when the Component is not required
or removed.
• Following are the methods available in unmount state:
ComponentWillUnmount(): called when the Component is removed or destroyed.
import React, {Component} from 'react';
this.UpdateName = this.UpdateName.bind(this);
this.testclick = this.testclick.bind(this);
}
UpdateName(event) {
this.setState({name: event.target.value});
}
testclick(event) {
alert("The name entered is: "+ this.state.name);
}
componentDidMount() {
console.log('Mounting State : calling method componentDidMount');
}
shouldComponentUpdate() {
console.log('Update State : calling method shouldComponentUpdate');
return true;
}
componentDidUpdate() {
console.log('Update State : calling method
componentDidUpdate')
}
componentWillUnmount() {
console.log('UnMounting State : calling method
componentWillUnmount');
}
render() {
return (
<div>
Enter Your Name:<input type="text"
value={this.state.name} onChange={this.UpdateName} /><br/>
<h2>{this.state.name}</h2>
<input type="button"
value="Click Here"
onClick={this.testclick} />
</div>
);
}
}
componentDidUpdate(){
if(this.props.users.length == 0)
throw new Error("No users in list!")
}
...
• Error boundaries are React components that catch JavaScript errors anywhere in their child
component tree, log those errors, and display a fallback UI instead of the component tree that
crashed. Error boundaries catch errors during rendering
• https://reactjs.org/docs/error-boundaries.html
• React.Component – React (reactjs.org)
state = {
name:'',
onservation:'',
color:'',
size:'',
}
handleChanges = (event) => {
let name = event.target.name;
let val = event.target.value;
this.setState({[name]: val});
console.log(this.state)
};
submitFormHandler = (event) => {
event.preventDefault();
console.log("from submit ", this.state);
};
render(){
const colors = ['Blue', 'Red', 'Green', 'Yellow'];
const sizes = ['Small', 'Medium', 'Large', 'XL', 'XXL', '3XL'];
return (
<form onSubmit={this.submitFormHandler}>
<div className='form-control'>
<label>Name:</label>
<input name="name" type="text" value={this.state.name} onChange={this.handleChanges} />
</div>
<div className='form-control'>
<label>Observation:</label>
<textarea name="observation" value={this.state.observation} onChange={this.handleChanges} />
</div>
<div className='form-control'>
<label>Desired color:</label>
<select name="color" value={this.state.color} onChange={this.handleChanges}>
{colors.map((color, i) => <option key={i} value={color.toLowerCase()}>{color}</option>)}
</select>
</div>
<div >
<label>T-shirt Size:</label>
{sizes.map((size, i) =>
<label key={i}> {size}
<input
name="size" value={size.toUpperCase()} checked={this.state.size === size.toUpperCase()}
onChange={this.handleChanges} type="radio" />
</label>
)}
</div>
<div className="form-actions">
<button type="submit">Submit</button>
</div>
</form>
)}
}
export default MultipleInputFields;
Controlled components : Summary
• A controlled component is bound to a value, and its adjustments will be
handled in code by using event-based callbacks.
Here, the input form variable is handled by the react itself rather than the DOM.
In this case, the mutable state is maintained in the state property and modified using
setState().
• Controlled components have functions which regulate the data that occurs at
each on Change event.
This data is subsequently saved in the setState() method and updated. It helps
components manage the elements and data of the form easier.
•
• You can use the controlled component when you create:
Forms validation so that when you type, you always have to know the input value to
verify whether it is true or not!
Disable submission icon, except for valid data in all fields
If you have a format such as the input for a credit card
Validation
class ControlledInputValidation1 extends React.Component {
state = { age: '' };
Uncontrolled components are inputs that do not have a value property. In opposite
to controlled components, it is the application's responsibility to keep the component
state and the input value in sync.
Uncontrolled Inputs
• In uncontrolled components form
data is being handled by DOM itself.
• For example here we can reference
form values by name
• This is quick and dirty way of handling
forms. It is mostly useful for simple
forms or when you are just learning
React.
Uncontrolled Inputs
import React, {Component} from 'react'; • You initialize a new ref in the
class SimpleForm extends Component { constructor by calling
constructor(props) { React.createRef, assigning it to
super(props); an instance property so it’s
// create a ref to store the DOM element available for the lifetime of the
this.nameEl = React.createRef(); component.
} • In order to associate the ref with
an input, it’s passed to the
handleSubmit = (e) => { element as the
e.preventDefault(); special ref attribute.
alert(this.nameEl.current.value); • Once this is done, the input’s
} underlying DOM node can be
accessed via
render() { this.nameEl.current.
return (
<form onSubmit={this.handleSubmit}>
<label>Name:
<input type="text" ref={this.nameEl} />
</label>
<input type="submit" name="Submit" />
</form>
)
}
}
export default SimpleForm;
class LoginForm extends Component {
constructor(props) {
super(props);
Another example : Login form
this.nameEl = React.createRef();
this.passwordEl = React.createRef();
this.rememberMeEl = React.createRef();
}
handleSubmit = (e) => {
e.preventDefault();
const data = {
username: this.nameEl.current.value,
password: this.passwordEl.current.value,
rememberMe: this.rememberMeEl.current.checked,
}
console.log(data)
}
render(){
return (
<form onSubmit={this.handleSubmit}>
<fieldset><legend>Login Form</legend>
<input type="text" placeholder="username" ref={this.nameEl} /><br></br>
<input type="password" placeholder="password" ref={this.passwordEl} /><br></br>
<label><input type="checkbox" ref={this.rememberMeEl} />Remember me
</label><br></br>
<button type="submit" className="myButton">Login</button>
</fieldset>
</form>
);
}}
methodA() {
console.log("methodA in parent class"); Console output
}
render() {
return false;
}
}
Composition
• Composition is a code reuse technique where a larger object is created by
combining multiple smaller objects.
function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
CONTEXT
Context
• Context is designed to share data that can be considered “global” for a tree of React
components, such as the current authenticated user, theme, or preferred language
function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
// Here we don't use the Context directly, but render children that do.
const AccountSummary = (props) => {
return (
<AccountSummaryHeader/>
<AccountSummaryDashboard/>
<AccountSummaryFooter/>
);
};
All three of these child components may not want to access the current user’s data. But as
an example, let’s just look at the AccountSummaryHeader component:
const AccountSummaryHeader = (props) => {
// Here we retrieve the current value of the context
const context = React.useContext(UserContext);
return (
<section><h2>{context.currentUser.name}</h2> </section>
);
};
Context
• Using context, we can avoid passing props through intermediate elements
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
// A component in the middle doesn't have to pass the theme down explicitly anymore
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
}
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}
render(){
return(
<div className=“container”>
<h1 className="text-danger">TODO LIST </h1>
REDUX
Because state management can be hard
What is state
• Eg: const state = { <div className={this.state.signUpModal.open ? 'hidden' : ''}>
posts: [], Sign Up Modal
signUpModal: { </div>
open: false
}
}
//REDUCER
//DISPATCH
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Create a Redux application
import {createStore} from 'redux’;
• Step-1 : Create the store: const myStore = createStore(reducer-name)
• A reducer is a function that receives the current state and an action object,
decides how to update the state if necessary, and returns the new state:
(state, action) => newState.
You can think of a reducer as an event listener which handles events based on the
received action (event) type.
• The Redux store has a method called dispatch. The only way to update the
state is to call store.dispatch() and pass in an action object.
The store will run its reducer function and save the new state value inside, and we
can call getState() to retrieve the updated value:
My original index.js
//original React imports let store = createStore(counter);
import {createStore} from 'redux';
//Display it in console
//STORE -> GLOBALISED STATE store.subscribe(() =>
console.log(store.getState()));
//ACTION -> INCREMENT
const increment = () => { //DISPATCH
return { store.dispatch(increment());
type :'INCREMENT' //name of the action store.dispatch(decrement());
}
} ReactDOM.render(
const decrement = () => { <React.StrictMode>
return { <App />
type :'DECREMENT' //name of the action </React.StrictMode>,
} document.getElementById('root')
} );
//REDUCER
const counter = (state=0, action) => {
switch(action.type){
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
}
}
//reducers/counter.js
const counterReducer = (state=0, action) => { Create a Redux app
switch(action.type){
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1; //src/index.js
default: return null; import {createStore} from 'redux';
} import allReducers from "./reducers";
}
export default counterReducer; const store = createStore(allReducers);
//reducers/isLogged.js
const loggedReducer = (state=false, action) => {
switch(action.type){
case "SIGNIN": //reducers/index.js
return !state; import counterReducer from "./counter";
default: import loggedReducer from "./isLogged";
return state; import {combineReducers} from 'redux';
}
} const allReducers = combineReducers({
export default loggedReducer; counter : counterReducer,
isLogged:loggedReducer
})
export default allReducers;
//src/index.js
//Original code:
const store = createStore(allReducers);
//New code:
const store = createStore(allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && windo
w.__REDUX_DEVTOOLS_EXTENSION__());
//src/index.js
import {createStore} from 'redux';
import allReducers from "./reducers"; const counterReducer =
import {Provider} from 'react-redux'; (state=0, action) => {…}
ReactDOM.render(
<React.StrictMode>
<Provider store={myStore}>
<App />
</Provider>
</React.StrictMode>,
App.js : displaying state Allows you to extract data
from the Redux store
state, using a selector
import './App.css'; function.
import {useSelector} from 'react-redux';
function App() {
const counter = useSelector(state => state.counter);
const isLogged = useSelector(state => state.isLogged);
return (
<div className="App"> I set the isLogged
<h1>Welcome to Redux</h1> state to true
<h3>Counter : {counter}</h3>
{isLogged ? <h3> Some valuable info here</h3> : ''}
</div>
);
}
//actions/index.js
Modifying state export const increment = () => {
return {
type :'INCREMENT'
}
}
export const decrement = () => {
import './App.css';
return {
import {useSelector, useDispatch} from 'react-redux';
type :'DECREMENT'
import {increment} from './actions';
}
import {decrement} from './actions';
}
function App() {
const counter = useSelector(state => state.counter);
const isLogged = useSelector(state => state.isLogged);
const dispatch = useDispatch();
return (
<div className="App">
<h1>Welcome to Redux</h1>
<h3>Counter : {counter}</h3>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
{isLogged ? <h3> Some valuable info here</h3> : ''}
</div>
);
}
export default App;