0% found this document useful (0 votes)
46 views59 pages

Is - FSD Notes

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

Is - FSD Notes

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

BIS601 Fullstack Development VIsem c sec(IS)

FULL STACK DEVELOPMENT NOTES (BIS601)

Staff In-charge: SJ Shaheena Begum


Asst. Professor

GHOUSIA COLLEGE OF ENGINEERNG, RAMANAGARA 562159


Department of Computer Science and Engineering

1
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Syllabus:
Module-1 Basic JavaScript Instructions, Statements, Comments, Variables, Data Types, Arrays,
Strings, Functions, Methods & Objects, Decisions & Loops.

Module-2 Document Object Model: DOM Manipulation, Selecting Elements, Working with DOM Nodes,
Updating Element Content & Attributes, Events, Different Types of Events, How to Bind an Event to an
Element, Event Delegation, Event Listeners

Module-3 Form enhancement and validation. Introduction to MERN: MERN components, Server
less Hello world. React Components: Issue Tracker, React Classes, Composing Components,
Passing Data Using Properties, Passing Data Using Children, Dynamic Composition.

Module-4 React State: Initial State, Async State Initialization, Updating State, Lifting State Up,
Event Handling, Stateless Components, Designing Components, State vs. Props, Component
Hierarchy, Communication, Stateless Components.
Express, REST API, GraphQL, Field Specification, Graph Based, Single Endpoint, Strongly Typed,
Introspection, Libraries, The About API GraphQL Schema File, The List API, List API Integration,
Custom Scalar types, The Create API, Create API Integration, Query Variables, Input Validations,
Displaying Errors.

Module-5 MongoDB: Basics, Documents, Collections, Databases, Query Language, Installation,


The Mongo Shell, MongoDB CRUD Operations, Create, Read, Projection, Update, Delete,
Aggregate, MongoDB Node.js, Driver, Schema Initialization, Reading from MongoDB, Writing to
MongoDB. Modularization and Webpack, Back-End Modules Front-End Modules and Webpack
Transform and Bundle, Libraries Bundle ,Hot Module Replacement, Debugging Define Plugin:
Build Configuration, Production Optimization.

2
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

JavaScript: JavaScript is a versatile, object-oriented scripting language that enables the creation of
interactive web pages and runs seamlessly across multiple platforms. In addition to its client-side
capabilities, JavaScript has server-side variants like Node.js, which unlock enhanced website
functionality, enabling developers to craft more dynamic, engaging, and feature-rich online
experiences that go beyond simple file downloads.
Client-side JavaScript builds upon the core language by providing a set of objects that enable
control over the browser and its Document Object Model (DOM). With these extensions,
developers can create dynamic web applications that interact with users in various ways, such as
adding elements to HTML forms, handling user input, responding to mouse clicks, and reacting to
page navigation events. This allows for a more engaging and interactive user experience.
Server-side JavaScript expands the core language by introducing objects tailored for server-side
execution. These extensions empower applications to interact with databases, maintain session state
between invocations, and perform file operations on the server, thereby enabling more complex and
data-driven web applications. This allows developers to build robust, scalable, and dynamic server-
side logic that integrates seamlessly with various data sources and services.
Why JS?
1. Scripting language
2. Light weight and purely object based language
3. JS is high-level language which gets executed on the browser, to execute JS instructions it is
mandatory to translate JS instruction into machine understandable language, this job is done by JS
engine
4. client-side language
5. JS is loosely typed and dynamic typed language - To giving the functionality to the webpage,
without reloading the page It is case-sensitive (but html and CSS are casein sensitive)
6. It is interpreted language - means it is interpreted line by line or execute line by line
7. It is synchronous: it is follows only one stack; example books arrangement in library, (LIFO)
Last in first out: memory representation

Difference between Java and JavaScript :

Sl.no Java JavaScript

1. It is a programming language It is a scripting


language

2. It is multi-threaded It is single-threaded

3. it uses more memory it uses less memory

3
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

4. It runs on JVM It runs on


browser(JS engine)

5. It is not completely object oriented. Because, It is purely object oriented


it as primitive data-type such as byte, int, short,
Boolean, float, double, char. Which is not object.
6. It is strictly/strongly typed It is weekly typed
7. It Cannot be modified. Memory It can be modified.
is constant.
ex: int a=20; once the memory is
allocated means cannot be
modified,
8. It is independent language to run and execute It is dependent language
(run on browser)

List of JavaScript Engines:

-edge/Internet Explorer: Chakra

Basic JavaScript Instructions:


JavaScript instructions, also known as statements, are the building blocks of a JavaScript program.
They are used to perform specific actions, such as:

 Declaring variables
 Assigning values
 Executing functions
 Controlling flow (e.g., if/else, loops)
 Manipulating data

These instructions are executed by the JavaScript engine, allowing the program to interact with
users, manipulate data, and produce desired outcomes. Think of them as individual commands that,
when combined, create a JavaScript program.

// Create variables for the welcome message


var greeting = 'Hello';
var name = 'Mady';
var message = ', please check your order:';
// Concatenate the three variables above to create the welcome message

4
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

var welcome = greeting + name + message;

// Create variables to hold details about the sign


var sign = 'Montague House';
var tiles = sign.length;
var subTotal = tiles * 5;
var shipping = 7;
var grandTotal = subTotal + shipping;

// Get the element that has an id of greeting


var el = document.getElementById('greeting');
// Replace the content of that element with the personalized welcome message
el.textContent = welcome;
// Get the element that has an id of userSign then update its contents
var elSign = document.getElementById('userSign');
elSign.textContent = sign;

// Get the element that has an id of tiles then update its contents
var elTiles = document.getElementById('tiles');
elTiles.textContent = tiles;

// Get the element that has an id of subTotal then update its contents
var elSubTotal = document.getElementById('subTotal');
elSubTotal.textContent = '$' + subTotal;

// Get the element that has an id of shipping then update its contents
var elShipping = document.getElementById('shipping');
elShipping.textContent = '$' + shipping;

// Get the element that has an id of grandTotal then update its contents

5
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

var elGrandTotal = document.getElementById('grandTotal');


elGrandTotal.textContent = '$' + grandTotal;
// Note: textContent does not work in IE8 or earlier - see explanation on website

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML or innerText.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Syntax Basics
Understanding statements, variable naming, whitespace, and other basic JavaScript syntax.
A simple variable declaration
var foo = ’hello world ’;
Whitespace has no meaning outside of quotation marks
var foo = ’hello world ’;
Parentheses indicate precedence
2 * 3 + 5; // returns 11; multiplication happens first
2 * (3 + 5); // returns 16; addition happens first
Tabs enhance readability, but have no special meaning
var foo = function () {
console . log ( ’hello ’);
};

Object it is block of memory which has states (variables) and behaviour (methods), and stores in
key and value pair.
Console.log("Hello World")
Console. log ( “data” );

Console: It is object in JavaScript. It will help you (user/programmer) to uses variables and
functions present in the object.
Log: it is a function which accepts arguments. Log is member of console. (Present inside the
console)
Output methods:
There are five methods; Alert, Prompt, Confirm, Console.log, document.write

6
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

a. Alert: it gives alert window.


Ex: var d=10;
alert(d)
b. prompt: to get input from the user we use prompt
ex: Write a code to read text from the browser using the prompt and display number of characters
present in the text
var str=prompt();
var n= str.length;
console.log( str);
console.log( `number of characters in text are ${n}`);
c. Waring:
Console.warn(“this is waring message”) - It shows warning -
d. Error:
Console.error(“this is error”); - It shows error message

JavaScript Statements
Example:
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
JavaScript statements are composed of Values, Operators, Expressions, Keywords, and Comments.
The statements are executed, one by one, in the same order as they are written. JavaScript programs
and JavaScript statements are also called JavaScript code. Semicolons separate JavaScript
statements. Add a semicolon at the end of each executable statement. Ending statements with
semicolon is not required, but highly recommended.
// How to create variables:
var x;
let y;
// How to use variables:
x = 5;
y = 6;
let z = x + y;

7
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

JavaScript Values
The JavaScript syntax defines two types of values:
 Fixed values
 Variable values
 Fixed values are called Literals.
 Variable values are called Variables.

Comments
JavaScript comments serve as a valuable tool for clarifying and documenting code, making it easier
to understand and maintain. Additionally, comments can be strategically used to temporarily
disable code execution, allowing developers to test alternative implementations or troubleshoot
issues without permanently deleting code segments. This flexibility streamlines the development
and debugging process.

Single Line Comments

Single line comments start with //. Any text between // and the end of the line will be ignored by
JavaScript (will not be executed). This example uses a single-line comment before each code line:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2

Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
/*
This is a multi-line comment
that spans multiple lines
*/
Variables: variables are used to store and manipulate data. Variables can be declared in 4 ways:
Variables can be reassigned (except for const).
Variables can be declared without an initial value.
JavaScript is dynamically typed, meaning variable types can change during execution.

Variables can be declared using the following keywords:


 var: Introduced in the original JavaScript, var is function-scoped.
 let: Introduced in ECMAScript 2015 (ES6), let is block-scoped.
 const: Also introduced in ES6, const is block-scoped and cannot be reassigned.

Rules for JavaScript variable names:

underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

8
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Variable Types
JavaScript variables can hold various data types, including:

 Numbers
 Strings
 Booleans
 Arrays
 Objects
 Null
 Undefined

Declaring (Creating) JavaScript Variables


Creating variables in JavaScript is most often referred to as "declaring" variables.
You can declare JavaScript variables with the var statement:
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Scorpio";
After the execution of the statements above, the variable x will hold the value 5, and carname will
hold the value Scorpio.
Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables


If you assign values to variables that have not yet been declared, the variables will automatically be
declared.
These statements:
x=5;
carname="Scorpio";
have the same effect as:
var x=5;
var carname="Scorpio";
Redeclaring JavaScript Variables
If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;
After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.

Data Types:
It is a type of data, every variable has datatype that represents what kind of data is being stored in a variable.

Types of Data Type: Primitive Data type, Non -Primitive Data type
-defined data type provided by JS language and
it is immutable.
Types: Number, String, Boolean, Null, Undefined, BigInt, Symbol

9
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

-Primitive Data user defined data type, it is also called as reference type, and created by programmer
and it is mutable.
Types: Arrays, objects and functions etc.
can be change

While using identifier inside console, do not use double quotes.

Primitive Data type:


-2 power 53-1) to (2 power 53-1)
le quotes), ''(single quotes),``(back ticks is used to print
multiple statements)

ccepting space. it is an empty space. it reserved a space. typeof null is object.

BigInt. number
less than 150 will be considered as Number data type. 1- number,1n- BigInt.

function.
Non-Primitive Datatype:
Arrays, functions and objects
Arrays: array is a single value, But in JS we use to store different elements i.e., heterogeneous
value.
Representing array in square braces []
Function: used to perform the operations.
Advantage: 1. code reusability
2. code extensibility or less coding

Operators
The operator = is used to assign values. The operator + is used to add values. The assignment operator = is
used to assign values to JavaScript variables. The arithmetic operator + is used to add values together.
Ex: y=5;
z=2;
x=y+z;
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Operator Description Example Result

10
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table
below explains the assignment operators:

Adding Strings and Numbers


Look at these examples:
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
The rule is:
If you add a number and a string, the result will be a string

JavaScript Comparison and Logical Operators


Comparison and Logical operators are used to test for true or false
Comparison Operators Comparison operators are used in logical statements to determine equality or
difference between variables or values. Given that x=5, the table below explains the comparison operators:

11
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Comparison operators can be used in conditional statements to compare values and take action depending
on the result: if (age<28)document.write(“too young”);

Logical Operators

Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the
table below explains the logical operators:

Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable
based on some condition

Syntax variablename=(condition)?value1:value2

Example greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear
President " else it will be assigned "Dear"

Strings: Sequence of characters is String, In JS String can be represented using ‘ ‘ ,” “, ` ` . Note: 1. The start
and end of a string must be done with the help of same quote.(`”,” ‘,’ “, these are not allowed.) 2. If a text
contains a single quote ten it can be represented using “ “.

Backtick: A Backtick can be a multi-line string. String represented using backtick is also known as
Template String.
The advantage of template string is we can substitute an expression in a string using ${expression}.

12
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Var hobbies=`my hobbies:


1. Swimming
2. Cycling
3. Running
4. Gaming `;
Console.log(hobbies);
Output: my hobbies:
1. Swimming
2. Cycling
3. Running
4. Gaming

+operator: +operator behaves like a concat operator if the operand is a string.


Ex: console.log(“I’m ”+name+” and I’m “+age+” years old”);
Concatenation:
Number with addition with String- Concatenation

String Methods:
1.IndexOf()
Syntax: IndexOf(str/chr) user can give string or character, it will return index value.
Character which is not present in the string then the output will be -1. first occurrence value..
But it can take 1st and 2nd character too
2. lastindesxof()
3. search() is similar to indexof, it only first occurrence value. Accept the, first search character
only one character. It not
accept two argument
4. Str.length:To check the length of the String
var str= "JAVA SCRIPT"
console.log(str.length);
5. Slice: To check the character in the index, using this we can extract some part of string. It will
accept the first or start index

13
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

and last index. Last digit will be work as length- 1, if (5, 9) 5 to 9-1=8, we can pass both positive
and negative value
var a = str.slice(0,4);
console.log(a);
6.Uppercase
var a= str.toUpperCase("script");
console.log(a);
7.Lowercase
17
var a = str.toLowerCase("java");
console.log(a);
8. Concat
Addition of two strings
var a="Java"
var b=" Script"
console.log(a.concat(b));
9. charAT : it specifies the position of the character
var str="JavaScript";
var char=str.charAt(1);
console.log(char);//a
10.charCodeAT: it converts to the ASCII value to the specified character
var str="JavaScript";
var char=str.charCodeAt(1);
console.log(char); //97
1. it repeat the string 3 times.
var char=str.repeat(3);
console.log(char);//JavaScriptJavaScriptJavaScript

11.replace(): it helps to replace the string.


var str='Pune to Bangaluru'

14
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

var char=str.replace("Pune", "Mangaluru");


console.log(char); //Mangaluru to Bangaluru

12.trim:It removes the space which is present at starting and endig position.
13.startWith
var car="JAVASCRIPT"
var char = str.startsWith(']');
console.log(char);
14.EndsWith
var car="JAVASCRIPT"
var char = str.endsWith(']');
console.log(char);
15. Split
Example 1:
var str=''MALL OF MYSORE';
var char=str.split('');
console.log(char);
Exampe 2:
var str='MALL OF MYSORE';
var char=str.split(' ');
18
console.log(char);// (2)[ 'MALL OF MYSORE']
Example 3:
var str='MALL OF MYSORE';
var char=str.split('| ');
console.log(char);// (1)[ 'MALL OF MYSORE']

16. Substring : substring () to extract the part of string, it is similar to slice but it won’t accept the
negative value or
.Substr(): start index and length of the character to be extracted. It will accept negative value.
using subscript [] we can access the character.

15
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

var str='MALL OF MYSORE';


var char=str.substring(0,5);
console.log(char);//MALL
17.InString:
var str=''MALL OF MYSORE';
var char=str.indexOf('O');
console.log(char);//5
18.INCLUDES:
var str='MALL OF MYSORE';
var char=str.includes('IN');
console.log(char);//false
var str='MALL IN MYSORE';
var char=str.includes('IN');
console.log(char);//true

Functions: In JavaScript, functions are blocks of code that can be executed multiple times from different
parts of a program.

main advantage of function is code reusability.

Syntax:
Function identifier (parameter 1, parameterc2)
{
Statements / code;
}

Function Declaration
Functions can be declared using the function keyword:
JavaScript
function greet(name) {
console.log(`Hello, ${name}!`);
}

16
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Function Expression
Functions can also be defined as expressions:
JavaScript
let greet = function(name) {
console.log(`Hello, ${name}!`);
}
Arrow Functions
Arrow functions are a concise way to define functions, introduced in ECMAScript 2015 (ES6):
JavaScript
let greet = (name) => {
console.log(`Hello, ${name}!`);
}
Function Parameters
Functions can take parameters, which are values passed to the function when it's called:
JavaScript
function add(a, b) {
return a + b;
}
Function Return Values
Functions can return values using the return statement:
JavaScript
function square(x) {
return x * x;
}
Function Invocation
Functions can be invoked (called) using the function name followed by parentheses:
JavaScript
greet('John'); // Output: Hello, John!
Function Scope
Functions have their own scope, which means variables defined inside a function are not accessible
outside the function:
JavaScript

17
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

function example() {
let x = 10;
console.log(x); // Output: 10
}
console.log(x); // ReferenceError: x is not defined
Higher-Order Functions
Higher-order functions are functions that take other functions as arguments or return functions as
output:
JavaScript
function map(arr, fn) {
return arr.map(fn);
}
Anonymous Functions
Anonymous functions are functions without a name:
JavaScript
let numbers = [1, 2, 3].map(function(x) {
return x * x;
});
Immediately Invoked Function Expressions (IIFE)
IIFE is a function that is called immediately after its definition:
JavaScript
(function() {
console.log('Hello, World!');
})();

Objects
Objects are collections of key-value pairs, where each key is a string and each value can be any data
type, including functions:
JavaScript
let person = {

18
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

name: 'John',
age: 30,
occupation: 'Developer'
};
Methods
Methods are functions that are properties of an object:
let person = {
name: 'John',
age: 30,
occupation: 'Developer',
greet: function() {
console.log(`Hello, my name is ${this.name}!`);
}
};
Accessing Object Properties
Object properties can be accessed using dot notation or bracket notation:
console.log(person.name); // Output: John
console.log(person['age']); // Output: 30
Creating Objects
Objects can be created using object literals, constructor functions, or the Object.create() method:
let person = new Object();
person.name = 'John';
person.age = 30;

Object Methods
Objects have built-in methods, such as hasOwnProperty(), keys(), and values():
JavaScript
console.log(Object.keys(person)); // Output: ['name', 'age', 'occupation']

19
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Constructor Functions
Constructor functions are used to create objects with a specific structure:
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person('John', 30);

Prototypes
Prototypes are objects that serve as templates for other objects:
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}!`);
};
Inheritance
Inheritance allows objects to inherit properties and methods from parent objects:
function Employee(name, age, occupation) {
Person.call(this, name, age);
this.occupation = occupation;
}
Employee.prototype = Object.create(Person.prototype);
Object-Oriented Programming (OOP) Concepts
JavaScript supports OOP concepts, such as encapsulation, inheritance, and polymorphism:
class Person {
constructor(name, age) {

20
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}!`);
}
}
class Employee extends Person {
constructor(name, age, occupation) {
super(name, age);
this.occupation = occupation;
}
}

Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You
can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code only if a specified condition is
true
if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
if...else if....else statement - use this statement if you want to select one of many blocks of code
to be executed
switch statement - use this statement if you want to select one of many blocks of code to be
executed

If Statement
You should use the if statement if you want to execute some code only if a specified condition is
true.
Syntax
if (condition)

21
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

{
code to be executed if condition is true
}
Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>

If...else Statement
If you want to execute some code if a condition is true and another code if the condition is not true,
use
the if....else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type="text/javascript">
//If the time is less than 10,

22
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

//you will get a "Good morning" greeting.


//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

If...else if...else Statement


You should use the if....else if...else statement if you want to select one of many sets of lines to
execute.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

23
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
Else
{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement


You should use the switch statement if you want to select one of many blocks of code to be
executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:

24
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

code to be executed if n is
different from case 1 and 2
}
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript Controlling(Looping) Statements


Loops in JavaScript are used to execute the same block of code a specified number of times or
while
a specified condition is true.
JavaScript Loops

25
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Very often when you write code, you want the same block of code to run over and over again in a
row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript there are two different kind of loops:
- loops through a block of code a specified number of times
- loops through a block of code while a specified condition is true
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run
as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing
statement.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

26
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript While Loop


Loops in JavaScript are used to execute the same block of code a specified number of times or
while a specified condition is true.
The while loop
The while loop is used when you want the loop to execute and continue executing while the
specified condition is true.
while (var<=endvalue)
{
code to be executed
}
Note: The <= could be any comparing statement.

Example
</html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)

27
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The do...while Loop


The do...while loop is a variant of the while loop. This loop will always execute a block of code
ONCE,
and then it will repeat the loop as long as the specified condition is true. This loop will always be
executed at least once, even if the condition is false, because the code is executed before the
condition is
tested.
do
{
code to be executed

28
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

}
while (var<=endvalue);
Example
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>
Result
The number is 0

JavaScript Break and Continue


There are two special statements that can be used inside loops: break and continue.
JavaScript break and continue Statements
There are two special statements that can be used inside loops: break and continue.
Break
The break command will break the loop and continue executing the code that follows after the loop
(if
any).
Example
<html>
<body>

29
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body></html>
Result

The number is 0

The number is 1

The number is 2

Continue
The continue command will break the current loop and continue with the next value.
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;

30
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

Module-2
Document Object Model: The Document object represents the entire HTML document and can be used to
access all elements in a page. The Document object is part of the Window object and is accessed through
the window.document property.

DOM Manipulation :In JavaScript, DOM (Document Object Model) manipulation is used to dynamically
change the structure and content of a web page.

, Selecting Elements, Working with DOM Nodes, Updating Element Content & Attributes, Events, Different
Types of Events, How to Bind an Event to an Element, Event Delegation, Event Listeners
Selecting Elements

31
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

To manipulate the DOM, you need to select the elements you want to work with:

document.getElementById(): Selects an element by its ID.

document.getElementsByClassName(): Selects elements by their class name.

document.getElementsByTagName(): Selects elements by their tag name.

document.querySelector(): Selects the first element that matches a CSS selector.

document.querySelectorAll(): Selects all elements that match a CSS selector.

let element = document.getElementById('myId');

Creating Elements

You can create new elements using the document.createElement() method:

let newElement = document.createElement('div');

Adding Elements

You can add elements to the DOM using the appendChild() or insertBefore() methods:

let parent = document.getElementById('parent');

let newElement = document.createElement('div');

parent.appendChild(newElement);

Removing Elements

You can remove elements from the DOM using the removeChild() or remove() methods:

let parent = document.getElementById('parent');

let child = document.getElementById('child');

parent.removeChild(child);

Modifying Elements

You can modify elements by changing their properties or attributes:

element.innerHTML: Sets or gets the HTML content of an element.

element.textContent: Sets or gets the text content of an element.

element.setAttribute(): Sets an attribute of an element.

element.removeAttribute(): Removes an attribute from an element.

32
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

let element = document.getElementById('myId');

element.innerHTML = 'New content';

Working with DOM nodes:

DOM nodes involves manipulating the elements and structure of a web page. Here's a comprehensive
overview:

Node Types

There are several types of nodes in the DOM:

Element nodes: Represent HTML elements, such as <div>, <p>, etc.

Text nodes: Represent text content within an element.

Attribute nodes: Represent attributes of an element, such as id, class, etc.

Comment nodes: Represent comments in the HTML code.

let element = document.getElementById('myId'); // Element node

let text = element.firstChild; // Text node

let attribute = element.getAttributeNode('id'); // Attribute node

Node Properties

Nodes have several properties that can be accessed and modified:

nodeName: Gets the name of the node.

nodeValue: Gets or sets the value of the node.

nodeType: Gets the type of the node.

parentNode: Gets the parent node of the current node.

childNodes: Gets a collection of child nodes.

firstChild: Gets the first child node.

lastChild: Gets the last child node.

nextSibling: Gets the next sibling node.

previousSibling: Gets the previous sibling node.

let element = document.getElementById('myId');

console.log(element.nodeName); // Output: DIV

console.log(element.nodeType); // Output: 1 (Element node)

33
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Node Methods

Nodes have several methods that can be used to manipulate the DOM:

appendChild(): Adds a new child node to the end of the list of child nodes.

insertBefore(): Inserts a new child node before the specified child node.

removeChild(): Removes the specified child node.

replaceChild(): Replaces the specified child node with a new node.

cloneNode(): Clones the current node and its child nodes.

let element = document.getElementById('myId');

let newElement = document.createElement('div');

element.appendChild(newElement);

Node Collections

Node collections are used to store and manipulate groups of nodes:

NodeList: A collection of nodes that can be accessed by index.

HTMLCollection: A collection of HTML elements that can be accessed by index or by name.

let elements = document.getElementsByTagName('div');

for (let i = 0; i < elements.length; i++) {

console.log(elements[i]);

DOM Manipulation

DOM manipulation involves creating, modifying, and removing nodes:

document.createElement(): Creates a new element node.

document.createTextNode(): Creates a new text node.

document.createAttribute(): Creates a new attribute node.

let element = document.createElement('div');

let text = document.createTextNode('Hello, World!');

element.appendChild(text);

Updating Element Content

There are several ways to update the content of an element:

34
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

innerHTML: Sets or gets the HTML content of an element.

textContent: Sets or gets the text content of an element.

innerText: Sets or gets the text content of an element, similar to textContent.

let element = document.getElementById('myId');

element.innerHTML = 'New content';

element.textContent = 'New text content';

Updating Element Attributes

There are several ways to update the attributes of an element:

setAttribute(): Sets the value of an attribute.

getAttribute(): Gets the value of an attribute.

removeAttribute(): Removes an attribute from an element.

let element = document.getElementById('myId');

element.setAttribute('class', 'new-class');

let className = element.getAttribute('class');

element.removeAttribute('class');

Updating Element Styles

There are several ways to update the styles of an element:

style property: Sets or gets the styles of an element.

classList property: Adds, removes, or toggles classes on an element.

let element = document.getElementById('myId');

element.style.color = 'red';

element.classList.add('new-class');

element.classList.remove('old-class');

element.classList.toggle('active');

Updating Element Classes

There are several ways to update the classes of an element:

className property: Sets or gets the classes of an element.

classList property: Adds, removes, or toggles classes on an element.

35
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

let element = document.getElementById('myId');

element.className = 'new-class';

element.classList.add('new-class');

element.classList.remove('old-class');

element.classList.toggle('active');

Events :

events are used to respond to user interactions, such as clicking a button, hovering over an element, or
submitting a form. OR

an Event is always the result of something a user does. For example, we've already seen Event Handlers like
onClick and onMouseOver that respond to mouse actions. Another type of Event, an internal change-of-
state to the page (completion of loading or leaving the page). An onLoad Event can be considered an
indirect result of a user action.

Event Types

There are several types of events in JavaScript:

Mouse events: click, dblclick, mousedown, mousemove, mouseout, mouseover, mouseup

Keyboard events: keydown, keypress, keyup

Form events: submit, reset, change, focus, blur

Document events: load, unload, resize, scroll

document.getElementById('myButton').addEventListener('click', function() {

console.log('Button clicked');

});

OR

Types of events that can be triggered by user interactions, browser actions, or other events. Here's a
comprehensive overview:

Mouse Events

Mouse events are triggered by user interactions with the mouse:

click: Triggered when a mouse button is clicked.

dblclick: Triggered when a mouse button is double-clicked.

mousedown: Triggered when a mouse button is pressed.

mousemove: Triggered when the mouse is moved.

mouseout: Triggered when the mouse is moved out of an element.

36
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

mouseover: Triggered when the mouse is moved over an element.

mouseup: Triggered when a mouse button is released.

document.getElementById('myButton').addEventListener('click', function() {

console.log('Button clicked');

});

Keyboard Events

Keyboard events are triggered by user interactions with the keyboard:

keydown: Triggered when a key is pressed.

keypress: Triggered when a key is pressed and released.

keyup: Triggered when a key is released

document.addEventListener('keydown', function(event) {

console.log('Key pressed:', event.key);

});

Form Events

Form events are triggered by user interactions with forms:

submit: Triggered when a form is submitted.

reset: Triggered when a form is reset.

change: Triggered when the value of a form element changes.

focus: Triggered when a form element receives focus.

blur: Triggered when a form element loses focus.

document.getElementById('myForm').addEventListener('submit', function(event) {

event.preventDefault();

console.log('Form submitted');

});

Document Events

Document events are triggered by browser actions or other events:

load: Triggered when a document is loaded.

unload: Triggered when a document is unloaded.

resize: Triggered when the browser window is resized.

scroll: Triggered when the browser window is scrolled.

window.addEventListener('load', function() {

37
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

console.log('Document loaded');

});

Touch Events

Touch events are triggered by user interactions with touch devices:

touchstart: Triggered when a touch event starts.

touchmove: Triggered when a touch event moves.

touchend: Triggered when a touch event ends.

touchcancel: Triggered when a touch event is cancelled.

document.addEventListener('touchstart', function(event) {

console.log('Touch started');

});

Pointer Events

Pointer events are triggered by user interactions with pointer devices:

pointerdown: Triggered when a pointer event starts.

pointermove: Triggered when a pointer event moves.

pointerup: Triggered when a pointer event ends.

pointercancel: Triggered when a pointer event is cancelled.

document.addEventListener('pointerdown', function(event) {

console.log('Pointer down');

});

Animation Events

Animation events are triggered by CSS animations:

animationstart: Triggered when an animation starts.

animationend: Triggered when an animation ends.

animationiteration: Triggered when an animation iteration starts.

document.addEventListener('animationstart', function(event) {

console.log('Animation started');

});

Transition Events

Transition events are triggered by CSS transitions:

transitionstart: Triggered when a transition starts.

38
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

transitionend: Triggered when a transition ends.

transitioncancel: Triggered when a transition is cancelled.

document.addEventListener('transitionstart', function(event) {

console.log('Transition started');

});

Binding an event to an element involves attaching a function to an event listener. Here's a step-by-step
guide:

Method 1: Using addEventListener()

let element = document.getElementById('myElement');

element.addEventListener('click', function() {

console.log('Element clicked');

});

Method 2: Using attachEvent()

let element = document.getElementById('myElement');

element.attachEvent('onclick', function() {

console.log('Element clicked');

});

Method 3: Using Inline Event Handlers

<button onclick="myFunction()">Click me</button>

function myFunction() {

console.log('Button clicked');

Method 4: Using jQuery

$('#myElement').on('click', function() {

console.log('Element clicked');

});

Event Listener Options

capture: A boolean value indicating whether the event should be captured or bubbled.

once: A boolean value indicating whether the event listener should be removed after the first invocation.

passive: A boolean value indicating whether the event listener should be passive.

39
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

let element = document.getElementById('myElement');

element.addEventListener('click', function() {

console.log('Element clicked');

}, {

capture: true,

once: true,

passive: true

});

Removing Event Listeners

You can remove event listeners using removeEventListener():

JavaScript

let element = document.getElementById('myElement');

element.removeEventListener('click', function() {

console.log('Element clicked');

});

Event Delegation

Event delegation is a technique where an event listener is attached to a parent element instead of
individual child elements. When an event occurs on a child element, it bubbles up to the parent element
and triggers the event listener.

To use event delegation, follow these steps:

Attach an event listener to a parent element: Use addEventListener() to attach an event listener to a parent
element.

Use the event.target property: Inside the event listener, use the event.target property to access the child
element that triggered the event.

Check the target element: Use an if statement or other logic to check if the target element is the one you're
interested in.

// Attach an event listener to the parent element

document.getElementById('parent').addEventListener('click', function(event) {

// Check if the target element is a child element

if (event.target.classList.contains('child')) {

console.log('Child element clicked');

});

40
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Example Use Case

Suppose you have a list of items and you want to handle clicks on each item. Instead of attaching an event
listener to each item, you can attach a single event listener to the parent list element and use event
delegation to handle clicks on each item.

HTML

<ul id="list">

<li class="item">Item 1</li>

<li class="item">Item 2</li>

<li class="item">Item 3</li>

</ul>

document.getElementById('list').addEventListener('click', function(event) {

if (event.target.classList.contains('item')) {

console.log('Item clicked:', event.target.textContent);

});

Event Listeners

You can add event listeners to elements to respond to user interactions:

element.addEventListener(): Adds an event listener to an element.

element.removeEventListener(): Removes an event listener from an element.

let element = document.getElementById('myId');

element.addEventListener('click', function() {

console.log('Element clicked');

});
OR
Event listeners are functions that are attached to elements and executed when a specific event
occurs, such as a click, hover, or submit.
Types of Event Listeners
There are several types of event listeners, including:
Inline event listeners: Functions that are defined directly in the HTML code.
External event listeners: Functions that are defined in a separate JavaScript file.
Anonymous event listeners: Functions that are defined without a name.

41
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

To use event listeners, follow these steps:


Select an element: Use a method such as document.getElementById() or document.querySelector()
to select an element.
Attach an event listener: Use the addEventListener() method to attach an event listener to the
element.
Define the event listener function: Define a function that will be executed when the event occurs.
// Select an element
let element = document.getElementById('myElement');
// Attach an event listener
element.addEventListener('click', function() {
console.log('Element clicked');
});
Removing Event Listeners
You can remove event listeners using the removeEventListener() method.
JavaScript
// Remove an event listener
element.removeEventListener('click', function() {
console.log('Element clicked');
});

Module-3

Form enhancement and validation: Both are crucial for creating user-friendly and secure web applications.

Form Enhancement

Form enhancement involves adding functionality to forms to improve the user experience:

Autocomplete: Suggesting possible values for form fields.

Placeholder text: Providing hints for form fields.

Form field validation: Checking form fields for errors.

Dynamic form fields: Adding or removing form fields dynamically.

Form Validation

Form validation involves checking form data for errors and providing feedback to the user:

Client-side validation: Validation that occurs on the client-side (in the browser).

42
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Server-side validation: Validation that occurs on the server-side (on the server).

Validation types: Different types of validation, such as required, email, and password.

JavaScript Form Validation

JavaScript can be used to validate forms on the client-side:

HTML5 validation: Using HTML5 validation attributes, such as required and pattern.

JavaScript validation: Using JavaScript to validate form fields.

// HTML5 validation

<input type="email" required>

// JavaScript validation

const form = document.getElementById('myForm');

form.addEventListener('submit', (e) => {

const email = document.getElementById('email').value;

if (!email.includes('@')) {

e.preventDefault();

alert('Invalid email address');

});

Form Validation Libraries

There are several form validation libraries available, including:

jQuery Validation: A popular jQuery plugin for form validation.

Validate.js: A lightweight JavaScript library for form validation.

Formik: A popular React library for form validation.

Example

Suppose you have a simple contact form with fields for name, email, and message. You can use JavaScript
to validate the form fields and provide feedback to the user.

<form id="contact-form">

<label for="name">Name:</label>

<input type="text" id="name" required>

<label for="email">Email:</label>

43
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

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

<label for="message">Message:</label>

<textarea id="message" required></textarea>

<button type="submit">Submit</button>

</form>

const form = document.getElementById('contact-form');

form.addEventListener('submit', (e) => {

const name = document.getElementById('name').value;

const email = document.getElementById('email').value;

const message = document.getElementById('message').value;

if (!name || !email || !message) {

e.preventDefault();

alert('Please fill out all fields');

} else if (!email.includes('@')) {

e.preventDefault();

alert('Invalid email address');

});

Introduction to MERN: MERN components:

MERN is a popular full-stack JavaScript framework used for building scalable and robust web applications.
MERN stands for MongoDB, Express.js, React.js, and Node.js. It's a collection of technologies that work
together to provide a comprehensive framework for building web applications.

MERN Components

The MERN stack consists of four main components:

MongoDB: A NoSQL database that stores data in JSON-like documents.

Express.js: A Node.js framework for building web applications and APIs.

React.js: A JavaScript library for building user interfaces and single-page applications.

Node.js: A JavaScript runtime environment that allows developers to run JavaScript on the server-side.

MongoDB

44
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

MongoDB is a NoSQL database that provides a flexible and scalable way to store data. Its key features
include:

Document-based data model: Data is stored in JSON-like documents.

Schema-less: No need to define a schema before storing data.

Scalability: Designed for horizontal scaling and high performance.

Express.js

Express.js is a Node.js framework that provides a lightweight and flexible way to build web applications and
APIs. Its key features include:

Request and response objects: Provides a simple way to handle HTTP requests and responses.

Middleware: Allows developers to add functionality to the application.

Routing: Provides a way to define routes for the application.

React.js

React.js is a JavaScript library that provides a way to build user interfaces and single-page applications. Its
key features include:

Components: Provides a way to build reusable UI components.

Virtual DOM: Provides a way to optimize rendering and improve performance.

State and props: Provides a way to manage state and props in components.

Node.js

Node.js is a JavaScript runtime environment that allows developers to run JavaScript on the server-side. Its
key features include:

JavaScript runtime: Allows developers to run JavaScript on the server-side.

Event-driven: Provides a way to handle events and callbacks.

Modules: Provides a way to manage dependencies and modules.

Server less Hello world: a simple "Hello World" example using a serverless function in a MERN (MongoDB,
Express.js, React.js, Node.js) stack:

Serverless Function (Node.js)

const mongoose = require('mongoose');

mongoose.connect('mongodb+srv://username:[email protected]/', {

useNewUrlParser: true,

useUnifiedTopology: true,

});

45
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

const helloWorldSchema = new mongoose.Schema({

message: String,

});

const HelloWorld = mongoose.model('HelloWorld', helloWorldSchema);

exports.handler = async (event) => {

const helloWorld = new HelloWorld({ message: 'Hello World!' });

await helloWorld.save();

return {

statusCode: 200,

body: JSON.stringify({ message: 'Hello World!' }),

};

};

This is a basic serverless function written in Node.js that connects to a MongoDB database and saves a
"Hello World!" message.

React.js Frontend

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

import axios from 'axios';

function App() {

const [message, setMessage] = useState('');

useEffect(() => {

axios.get('/api/hello-world')

.then((response) => {

setMessage(response.data.message);

})

.catch((error) => {

console.error(error);

46
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

});

}, []);

return (

<div>

<h1>{message}</h1>

</div>

);

export default App;

This is a basic React.js application that makes a GET request to the serverless function and displays the
response.

Express.js API Gateway

const express = require('express');

const app = express();

app.get('/api/hello-world', (req, res) => {

// Call the serverless function

const lambda = new AWS.Lambda({ region: 'your-region' });

const params = {

FunctionName: 'your-function-name',

InvocationType: 'RequestResponse',

};

lambda.invoke(params, (err, data) => {

if (err) {

console.error(err);

} else {

res.json(data.Payload);

});

});

47
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

app.listen(3000, () => {

console.log('Server listening on port 3000');

});

React Components:

React components are reusable pieces of code that represent a part of your user interface. They can be
thought of as custom HTML elements that can contain other components.

Types of React Components

There are two main types of React components:

Functional Components : These are the simplest type of component and are defined as a function.

Class Components : These are more complex components that are defined as a class.

Functional Components

Functional components are defined as a function and are the simplest type of component. They are easy to
write and understand.

import React from 'react';

function HelloWorld() {

return <h1>Hello World!</h1>;

Class Components

Class components are defined as a class and are more complex than functional components. They have
more features, such as state and lifecycle methods.

import React, { Component } from 'react';

class HelloWorld extends Component {

render() {

return <h1>Hello World!</h1>;

Issue Tracker: An issue tracker is a software application that helps teams track and manage issues, bugs,
and tasks throughout the development process. In React, an issue tracker can be built as a web application
that allows users to create, assign, and track issues.

Key Features of an Issue Tracker in React

48
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

 Issue creation : Users can create new issues and assign them to team members.
 Issue tracking : Users can track the status of issues and receive updates on their progress.
 Issue assignment : Users can assign issues to team members and track their progress.
 Prioritization : Users can prioritize issues based on their severity and impact.
 Filtering and sorting : Users can filter and sort issues based on various criteria, such as status,
priority, and assignee.
 Notifications : Users can receive notifications when issues are updated or assigned to them.

Technologies Used to Build an Issue Tracker in React

 React: A JavaScript library for building user interfaces.


 Node.js: A JavaScript runtime environment for building server-side applications.
 Express.js: A Node.js framework for building web applications.
 MongoDB: A NoSQL database for storing issue data.
 GraphQL: A query language for building APIs.

Issue Tracker Components

 IssueList: A component that displays a list of issues.


 IssueItem: A component that represents a single issue.
 IssueForm: A component that allows users to create new issues.
 IssueDetail: A component that displays the details of a single issue.

React Classes: React classes are a way to define components using the class keyword. They are used to
create components that have their own state and lifecycle methods.

Defining a React Class

To define a React class, you need to extend the React.Component class.

JavaScript

import React, { Component } from 'react';

class HelloWorld extends Component {

render() {

return <h1>Hello World!</h1>;

Class Components vs Functional Components

React classes are different from functional components in several ways:

State: Class components have their own state, while functional components do not.

49
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Lifecycle methods: Class components have lifecycle methods, such as componentDidMount and
componentWillUnmount, while functional components do not.

This keyword: Class components use the this keyword to refer to the component instance, while functional
components do not.

Class Component Lifecycle Methods

Class components have several lifecycle methods that are called at different points in the component's life
cycle:

constructor: Called when the component is initialized.

componentDidMount: Called when the component is mounted to the DOM.

componentDidUpdate: Called when the component's props or state change.

componentWillUnmount: Called when the component is unmounted from the DOM.

Class Component State

Class components have their own state, which can be updated using the setState method.

import React, { Component } from 'react';

class Counter extends Component {

constructor(props) {

super(props);

this.state = { count: 0 };

render() {

return (

<div>

<p>Count: {this.state.count}</p>

<button onClick={() => this.setState({ count: this.state.count + 1 })}>

Increment

</button>

</div>

);

Class Component Props

Class components can receive props from their parent components.

50
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

import React, { Component } from 'react';

class HelloWorld extends Component {

render() {

return <h1>Hello {this.props.name}!</h1>;

Composing Components: composing components is the process of combining smaller


components to create more complex ones.
Composing components is useful for several reasons:

 Reusability: By breaking down complex components into smaller ones, you can reuse them in other
parts of your application.
 Modularity: Composing components helps to keep your code organized and modular, making it easier
to maintain and update.
 Flexibility: Composing components allows you to create complex components that can be easily
customized and extended.

an example of composing components:

// Header.js

import React from 'react';

function Header() {

return <h1>This is a header</h1>;

export default Header;

// Footer.js

import React from 'react';

function Footer() {

return <p>This is a footer</p>;

export default Footer;

// App.js

import React from 'react';

51
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

import Header from './Header';

import Footer from './Footer';

function App() {

return (

<div>

<Header />

<p>This is the main content</p>

<Footer />

</div>

);

export default App;

Composing Components with Props

You can also compose components by passing props from a parent component to a child component.

// Button.js

import React from 'react';

function Button(props) {

return <button style={{ backgroundColor: props.color }}>{props.children}</button>;

export default Button;

// App.js

import React from 'react';

import Button from './Button';

function App() {

return (

<div>

<Button color="red">Click me!</Button>

</div>

);

52
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

export default App;

Passing Data Using Properties:

used to pass data from a parent component to a child component. Props are immutable,
meaning they cannot be changed once they are passed to a child component.

To pass props, you can add attributes to the child component when you use it in the parent
component.

JavaScript

// Parent component

import React from 'react';

import Child from './Child';

function Parent() {

return (

<div>

<Child name="John" age={30} />

</div>

);

// Child component

import React from 'react';

function Child(props) {

return (

<div>

<p>Name: {props.name}</p>

<p>Age: {props.age}</p>

53
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

</div>

);

}
Passing Data Using Children,: The children prop is a special prop in React that allows you to pass data from
a parent component to a child component. It is an array of React elements that are passed as children to a
component.

How to Pass Data Using Children

To pass data using children, you can wrap the child component in the parent component and pass the data
as a child element.

// Parent component

import React from 'react';

function Parent(props) {

return (

<div>

{props.children}

</div>

);

// Child component

import React from 'react';

function Child() {

return <p>This is a child component</p>;

// Using the Parent component with the Child component as a child

import React from 'react';

import Parent from './Parent';

import Child from './Child';

54
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

function App() {

return (

<Parent>

<Child />

</Parent>

);

Passing Multiple Children

You can pass multiple children to a component by wrapping multiple child elements in the parent
component.

// Parent component

import React from 'react';

function Parent(props) {

return (

<div>

{props.children}

</div>

);

// Child components

import React from 'react';

function Child1() {

return <p>This is child 1</p>;

function Child2() {

return <p>This is child 2</p>;

55
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

// Using the Parent component with multiple children

import React from 'react';

import Parent from './Parent';

import Child1 from './Child1';

import Child2 from './Child2';

function App() {

return (

<Parent>

<Child1 />

<Child2 />

</Parent>

);

Accessing Children in a Component

You can access the children of a component using the props.children property.

JavaScript

// Parent component

import React from 'react';

function Parent(props) {

return (

<div>

{React.Children.map(props.children, (child) => (

<div key={child.key}>{child}</div>

))}

</div>

);

56
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Dynamic Composition:

Dynamic composition is a technique in React where you can render different components or
elements based on certain conditions or user interactions. This allows you to create more flexible
and reusable components.
To Achieve Dynamic Composition
To achieve dynamic composition in React, you can use the following techniques:
 Conditional rendering: Use conditional statements to render different components or
elements based on certain conditions.
 Dynamic component rendering: Use dynamic component rendering to render different
components based on user interactions or other conditions.
 Higher-order components: Use higher-order components to wrap other components and
provide additional functionality.
Example of Dynamic Composition
Here's an example of dynamic composition in React:
import React, { useState } from 'react';
function DynamicComponent() {
const [showComponent1, setShowComponent1] = useState(true);
return (
<div>
{showComponent1 ? <Component1 /> : <Component2 />}
<button onClick={() => setShowComponent1(!showComponent1)}>Toggle</button>
</div>
);
}

function Component1() {
return <p>This is component 1</p>;
}

function Component2() {
return <p>This is component 2</p>;
}

57
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

Dynamic Component Rendering


Dynamic component rendering is a technique where you render different components based on user
interactions or other conditions.
import React, { useState } from 'react';
function DynamicComponent() {
const [component, setComponent] = useState('Component1');
return (
<div>
{component === 'Component1' ? <Component1 /> : <Component2 />}
<button onClick={() => setComponent('Component1')}>Show Component 1</button>
<button onClick={() => setComponent('Component2')}>Show Component 2</button>
</div>
);
}

function Component1() {
return <p>This is component 1</p>;
}

function Component2() {
return <p>This is component 2</p>;
}
Higher-Order Components
Higher-order components are a technique where you wrap other components and provide additional
functionality.
import React from 'react';
function withLogger(WrappedComponent) {
return function EnhancedComponent(props) {
console.log('Component rendered');
return <WrappedComponent {...props} />;
};

58
Dept. CSE, GCE -SJS-
BIS601 Fullstack Development VIsem c sec(IS)

}
function Component1() {
return <p>This is component 1</p>;
}
const EnhancedComponent1 = withLogger(Component1);

Module-4:
React State: Initial State, Async State Initialization, Updating State, Lifting State Up, Event Handling,
Stateless Components, Designing Components, State vs. Props, Component Hierarchy, Communication,
Stateless Components. Express, REST API, GraphQL, Field Specification, Graph Based, Single Endpoint,
Strongly Typed, Introspection, Libraries, The About API GraphQL Schema File, The List API, List API
Integration, Custom Scalar types, The Create API, Create API Integration, Query Variables, Input
Validations, Displaying Errors.

59
Dept. CSE, GCE -SJS-

You might also like