0% found this document useful (0 votes)
57 views54 pages

FSD Manual

The document outlines the syllabus for a Full Stack Development Lab course under JNTU Hyderabad, detailing prerequisites, course objectives, and outcomes. It includes a list of experiments focusing on web application development using Node JS, React, Express, and Angular, along with MongoDB operations. Reference books for further reading are also provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views54 pages

FSD Manual

The document outlines the syllabus for a Full Stack Development Lab course under JNTU Hyderabad, detailing prerequisites, course objectives, and outcomes. It includes a list of experiments focusing on web application development using Node JS, React, Express, and Angular, along with MongoDB operations. Reference books for further reading are also provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

R22 B.Tech.

CSE Syllabus JNTU Hyderabad

CS611PE: FULL STACK DEVELOPMENT LAB (Professional Elective – III)

B.Tech. III Year II Sem. LT P C


00 21
Pre-Requisites:
1.Object Oriented Programming
2.Web Technologies
Course Objectives:
 Introduce fast, efficient, interactive and scalable web applications using
run time environment provided by the full stack components.
Course Outcomes:
 Design flexible and responsive Web applications using Node JS, React,
Express and Angular.
 Perform CRUD operations with MongoDB on huge amount of data.
 Develop real time applications using react components.
 Use various full stack modules to handle http requests and responses.

List of Experiments

1.Create an application to setup node JS environment and display “Hello


World”.
2.Create a Node JS application for user login system.
3.Write a Node JS program to perform read, write and other operations on
a file.
4.Write a Node JS program to read form data from query string and
generate response using NodeJS
5.Create a food delivery website where users can order food from a
particular restaurant listed in the website for handling http requests and
responses using NodeJS.
6.Implement a program with basic commands on databases and collections
using MongoDB.
7.Implement CRUD operations on the given dataset using MongoDB.
8.Perform Count, Limit, Sort, and Skip operations on the given collections
using MongoDB.
9.Develop an angular JS form to apply CSS and Events.
10. Develop a Job Registration form and validate it using angular JS.
11. Write an angular JS application to access JSON file data of an
employee from a server using $http service.
12. Develop a web application to manage student information using
Express and Angular JS.
13. Write a program to create a simple calculator Application using React
JS.
14. Write a program to create a voting application using React JS
15. Develop a leave management system for an organization where users
can apply different types of leaves such as casual leave and medical leave.
They also can view the available number of days using react application.
16. Build a music store application using react components and provide
routing among the web pages.
17. Create a react application for an online store which consist of
registration, login, product information pages and implement routing to3
navigate through these pages.

REFERENCE BOOKS:

1.Vasan Subramanian, Pro MERN Stack, Full Stack Web App


Developmentwith Mongo,
Express, React, and Node, 2ndEdition, Apress,2019.
2.Chris Northwood, The Full Stack Developer: Your Essential Guide to the
Everyday Skills
Expected of a Modern Full Stack Web Developer’, 1stedition, Apress, 2018.
3.Brad Green& Seshadri. Angular JS. 1st Edition. O'Reilly Media, 2013.
4.Kirupa Chinnathambi, Learning React: A Hands-On Guide to Building
Web Applications Using
React and Redux, 2ndedition, Addison-Wesley Professional, 2018.
1. Create an application to setup node JS environment and display “Hello
World”.

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>hello world....</h1>');
res.end();
}).listen(8080);

Another way :
http = require('http');
listener = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World......');
};
server = http.createServer(listener);
server.listen(8080);

output :

>node hello1.js

2. Create a Node JS application for user login system.

Server.js
const http = require('http');
const url = require('url');
const querystring = require('querystring');
// Mock user data (in-memory storage)
const users = {
'vamshi': '123456', // username: password
};

// HTML pages for responses


const loginPage = `
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method='POST' action='/login'>
<label for='username'>Username:</label><br>
<input type='text' id='username' name='username' required><br><br>
<label for='password'>Password:</label><br>
<input type='password' id='password' name='password' required><br><br>
<button type='submit'>Login</button>
</form>
</body>
</html>
`;
const successPage = `
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Login Successful!</h1>

<a href='/'>Go back</a>


</body>
</html>
`;
const failurePage = `
<!DOCTYPE html>
<html>
<head>
<title>Failure</title>
</head>
<body>
<h1>Login Failed</h1>
<p>Invalid username or password.</p>
<a href='/'>Try Again</a>
</body>
</html>
`;
// Create HTTP server
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url);
const method = req.method;
if (parsedUrl.pathname === '/'&amp;&amp; method === 'GET') {
// Serve the login page
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(loginPage);
} else if (parsedUrl.pathname === '/login'&amp;&amp; method === 'POST') {
// Handle login form submission

let body = '';


// Collect POST data
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
const { username, password } = querystring.parse(body);
if (users[username] &amp;&amp; users[username] === password) {
// Login successful
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(successPage);
} else {
// Login failed
res.writeHead(401, { 'Content-Type': 'text/html' });
res.end(failurePage);
}
});
} else {
// Handle 404
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>');
}
});
// Start the server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);

});
3. Write a Node JS program to perform read, write and other
operations on a file.
readFile.js
//READ FILE
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('file1.txt', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

File1.txt
WELCOME TO MGIT CSE1 FULL STACK DEVELOPMENT

Output:
file1 content:WELCOME TO MGIT CSE1 FULL STACK DEVELOPMENT

writeFile.js
//WRITE FILE ASYNCHRONOUS CALL
var fs = require('fs');
fs.writeFile('file1.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
Output:
Replaced!

appendFile.js
//APPEND FILE ASYNCHRONOUS CALL
var fs = require('fs');
fs.appendFile('file1.txt', 'FULL STACK DEVELOPMENT', function (err) {
if (err) throw err;
console.log('Saved!');
});

Output:
Saved!
Deletefile.js
//DELETE FILE
var fs = require('fs');
fs.unlink('file2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});

Output:
'File deleted!
4. Write a Node JS program to read form data from query string and generate
response using NodeJS

var http = require('http');


var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q= url.parse(req.url,true).query;
console.log(q);
var txt = q.year + "" + q.month;
res.end(txt);
}).listen(8080);

OUTPUT :
5.Create a food delivery website where users can order food from a particular
restaurant listed in the website for handling http requests and responses
using NodeJS.

Server.js
const http = require('http');
const url = require('url');
// Sample menu data
const menu = [
{ id: 1, name: 'Pizza', price: 10 },
{ id: 2, name: 'Burger', price: 5 },
{ id: 3, name: 'Pasta', price: 8 },
];
// Handle HTTP requests
const requestListener = (req, res) => {
const { method, url: reqUrl } = req;
// Set content type to JSON
res.setHeader('Content-Type', 'application/json');
// Parse the URL to handle routing
const parsedUrl = url.parse(reqUrl, true);
const pathname = parsedUrl.pathname;
if (method === 'GET') {
if (pathname === '/menu') {
// Send the menu items
res.statusCode = 200;
res.end(JSON.stringify(menu));
} else if (pathname.startsWith('/order')) {
// Extract the order ID from the URL
const orderId = pathname.split('/')[2];
const orderItem = menu.find(item => item.id === parseInt(orderId));
if (orderItem) {
res.statusCode = 200;
res.end(JSON.stringify({ message: `Order placed for ${orderItem.name}` }));
} else {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Item not found' }));
}
} else {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Route not found' }));
}
} else {
res.statusCode = 405; // Method Not Allowed
res.end(JSON.stringify({ error: 'Method not allowed' }));
}
};
// Create server
const server = http.createServer(requestListener);
// Start server on port 3000
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
OUTPUT :
6. Implement a program with basic commands on databases and
collections using MongoDB.

MONGODB COMMANDS (CRUD OPERATIONS):


C-CREATE
R-READ/RETRIVE
U-UPDATE
D-DELETE

1. D:\MONGODB\DB>mongod --version
db version v8.0.0
Build Info: {
"version": "8.0.0",
"gitVersion": "d7cd03b239ac39a3c7d63f7145e91aca36f93db6",
"modules": [],
"allocator": "tcmalloc-gperf",
"environment": {
"distmod": "windows",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}
2.D:\MONGODB\DB>mongosh
Current Mongosh Log ID: 66f252c9808c7f3e6bc73bf7
Connecting to: mongodb://127.0.0.1:27017/?
directConnection=true&serverSelectionTimeoutMS=2000&appName=mongos
h+2.3.1
Using MongoDB: 8.0.0
Using Mongosh: 2.3.1
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2024-09-23T14:31:32.621+05:30: Access control is not enabled for the
database. Read and
write access to data and configuration is unrestricted
------
test>

3.test> show dbs


admin 40.00 KiB
config 72.00 KiB
local 72.00 KiB

4.test> use MYDB1


switched to db MYDB1
MYDB1> show dbs
admin 40.00 KiB
config 72.00 KiB
local 72.00 KiB

5.MYDB1> db.createCollection("students")
{ ok: 1 }

6.MYDB1> show dbs


MYDB1 8.00 KiB
admin 40.00 KiB
config 108.00 KiB
local 72.00 KiB

7.MYDB1> db.students.insertOne({"rollno":501 , "name":"cse1"})


{
acknowledged: true,
insertedId: ObjectId('66f255ec808c7f3e6bc73bf8')
}

8.MYDB1> show collections


Students

9.MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
}
]

10.MYDB1> db.students.insertOne({"rollno":502 , "name":"cse2"})


{
acknowledged: true,
insertedId: ObjectId('66f2577b808c7f3e6bc73bf9')
}

11.MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
},
{
_id: ObjectId('66f2577b808c7f3e6bc73bf9'),
rollno: 502,
name: 'cse2'
}
]

12.MYDB1> db.students.updateOne({rollno:502},{$set:{name:"cse3"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1
modifiedCount: 1,
upsertedCount: 0
}

13.MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
},
{
_id: ObjectId('66f2577b808c7f3e6bc73bf9'),
rollno: 502,
name: 'cse3'
}
]
14. MYDB1> db.students.deleteOne({rollno:111})
{ acknowledged: true, deletedCount: 1 }
MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}
]

15.MYDB1> db.students.drop()
True

16.MYDB1> show collections

17.MYDB1> db.dropDatabase()
{ ok: 1, dropped: 'MYDB1' }

18.MYDB1> show dbs


admin 40.00 KiB
config 108.00 KiB
local 72.00 KiB

inserting documents from java scripts:


db1.js
db.students.insertOne({name: "Karthik", rollno: 101, marks: 98 })
db.students.insertOne({name: "Ravi", rollno: 102, marks: 99 })
db.students.insertOne({name: "Shiva", rollno: 103, marks: 100 })
db.students.insertOne({name: "Pavan", rollno: 104, marks: 80 })
MYDB1> load('d:\db1.js')
True

MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
},
{
_id: ObjectId('670ded507a61ecab52c73bf8'),
name: 'Karthik',
rollno: 101,
marks: 98
},
{
_id: ObjectId('670ded507a61ecab52c73bf9'),
name: 'Ravi',
rollno: 102,
marks: 99
},
{
_id: ObjectId('670ded507a61ecab52c73bfa'),
name: 'Shiva',
rollno: 103,
marks: 100
},
{
_id: ObjectId('670ded507a61ecab52c73bfb'),
name: 'Pavan',
rollno: 104,
marks: 80
}
]
MYDB1> db.students.findOne()
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}
MYDB1> db.students.findOne({'name':'cccccc'})
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}

7.Implement CRUD operations on the given dataset using MongoDB.


Adding the MongoDB Driver to Node.js

1.npm install mongodb


added 12 packages, and audited 30 packages in 2s
found 0 vulnerabilities
Connect.js

// Connect to database and close the database connection


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Connect to database
client.connect()
.then(() => {
console.log('Connected Successfully!')
//Close the database connection
console.log('Exiting..')
client.close()
})
.catch(error => console.log('Failed to connect!', error))

Output:
MONGODB> node connect.js
Connected Successfully!
Exiting..

Insertdb.js

// to insert one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students').insertOne({
name: 'cse1',
email: '[email protected]'
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))

Output:

MONGODB> node insertdb.js


{
acknowledged: true,
insertedId: new ObjectId('674aeea8b3bc707da2d4559f')
}

Finddb.js

//to find one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.findOne({name:'cse1'})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))

Output:

MONGODB>node finddb.js
{
_id: new ObjectId('674aeea8b3bc707da2d4559f'),
name: 'cse1',
email: '[email protected]'
}
Updatedb.js

//to update one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.updateOne({ name: 'cse1' },
{
$set:
{ email: '[email protected]' }
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))

Output:
MONGODB> node updatedb.js

{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}

Deletedb.js

//to delete one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.deleteOne({ name: 'cse1' })
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))

Output:

MONGODB> node deletedb.js


{ acknowledged: true, deletedCount: 1 }
8. Perform Count, Limit, Sort, and Skip operations on the given collections using
MongoDB.

test> use MYDB2


switched to db MYDB2

MYDB2> db.createCollection("employees");
{ ok: 1 }
MYDB2> db.employees.insertMany([{'id':111, 'name':'aaaa', 'salary':10000},
{'id':222,'name':'bbbb', 'salary':30000},{'id':333, 'name':'cccc',
'salary':20000},{'id':444,'name':'dddd', 'salary':10000}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('6713c7d9b34f42f350c73bfc'),
'1': ObjectId('6713c7d9b34f42f350c73bfd'),
'2': ObjectId('6713c7d9b34f42f350c73bfe'),
'3': ObjectId('6713c7d9b34f42f350c73bff')
}
}
MYDB2> db.employees.find().pretty()
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().count()
4
MYDB2> db.employees.find({salary:10000}).count()
2
MYDB2> db.employees.find().pretty().limit(1)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().limit(2)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
}
]
MYDB2> db.employees.find().pretty().skip(2)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().skip(3)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().sort({id:1})
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().sort({id:-1})
[
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
}
]

9. Develop an angular JS form to apply CSS and Events.

HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Form with CSS and Events</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<style>
.error {
color: red;
font-size: 0.8em;
}
.valid {
color: green;
}
.highlight {
background-color: yellow;
}
.bold {
font-weight: bold;
}
</style>
</head>
<body ng-controller="FormController">

<h2>User Information Form</h2>

<form name="userForm" ng-submit="submitForm()" novalidate>


<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" ng-model="user.name" required
ng-class="{'error': userForm.name.$invalid && userForm.name.
$touched, 'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="userForm.name.$invalid && userForm.name.$touched"
class="error">Name is required.</div>
</div>

<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" ng-model="user.email" required
ng-class="{'error': userForm.email.$invalid && userForm.email.
$touched, 'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="userForm.email.$error.required && userForm.email.$touched"
class="error">Email is required.</div>
<div ng-show="userForm.email.$error.email && userForm.email.$touched"
class="error">Invalid email format.</div>
</div>

<div>
<label for="age">Age:</label>
<input type="number" id="age" name="age" ng-model="user.age" min="18"
ng-class="{'error': userForm.age.$invalid && userForm.age.$touched,
'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="userForm.age.$error.min && userForm.age.$touched"
class="error">Age must be at least 18.</div>
</div>

<div>
<label for="city">City:</label>
<select id="city" name="city" ng-model="user.city"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"
ng-change="cityChanged()">
<option value="">-- Select City --</option>
<option value="Karimnagar">Karimnagar</option>
<option value="Hyderabad">Hyderabad</option>
<option value="Warangal">Warangal</option>
<option value="Other">Other</option>
</select>
</div>

<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" ng-model="user.gender"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Male
<input type="radio" name="gender" value="female" ng-model="user.gender"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Female
</div>

<div>
<label>Interests:</label>
<input type="checkbox" name="interests" value="sports" ng-
model="user.interests.sports"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Sports
<input type="checkbox" name="interests" value="music" ng-
model="user.interests.music"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Music
<input type="checkbox" name="interests" value="reading" ng-
model="user.interests.reading"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Reading
</div>

<button type="submit" ng-disabled="userForm.$invalid"


ng-mouseover="toggleBold(true)" ng-mouseout="toggleBold(false)"
ng-class="{'bold': isBold}">Submit</button>

<div ng-show="submissionMessage"
class="{{submissionStatus}}">{{submissionMessage}}</div>
</form>

<script>
angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.user = {
name: '',
email: '',
age: null,
city: '',
gender: '',
interests: {
sports: false,
music: false,
reading: false
}
};

$scope.isHighlighted = false;
$scope.isBold = false;
$scope.submissionMessage = '';
$scope.submissionStatus = '';

$scope.highlightInput = function() {
$scope.isHighlighted = true;
};

$scope.unhighlightInput = function() {
$scope.isHighlighted = false;
};

$scope.toggleBold = function(isMouseOver) {
$scope.isBold = isMouseOver;
};

$scope.cityChanged = function() {
console.log('Selected city:', $scope.user.city);
// You can perform actions based on the selected city here
};

$scope.submitForm = function() {
if ($scope.userForm.$valid) {
console.log('Form submitted:', $scope.user);
$scope.submissionMessage = 'Form submitted successfully!';
$scope.submissionStatus = 'valid';
// You would typically send this data to a server here
} else {
console.log('Form is invalid.');
$scope.submissionMessage = 'Please correct the form errors.';
$scope.submissionStatus = 'error';
}
};
});
</script>

</body>
</html>

10. Develop a Job Registration form and validate it using angular JS

HTML
<!DOCTYPE html>
<html ng-app="jobRegistrationApp">
<head>
<title>Job Registration Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<style>
.error {
color: red;
font-size: 0.8em;
}
.valid {
color: green;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"],
input[type="email"],
input[type="tel"],
select,
textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button[type="submit"] {
background-color: #007bff;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button[type="submit"]:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.success-message {
color: green;
margin-top: 10px;
}
</style>
</head>
<body ng-controller="JobRegistrationController">

<h2>Job Registration Form</h2>

<form name="jobForm" ng-submit="submitForm()" novalidate>


<div class="form-group">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" ng-model="formData.name"
required>
<div ng-show="jobForm.name.$invalid && jobForm.name.$touched"
class="error">Full Name is required.</div>
</div>

<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" ng-
model="formData.email" required>
<div ng-show="jobForm.email.$error.required && jobForm.email.
$touched" class="error">Email Address is required.</div>
<div ng-show="jobForm.email.$error.email && jobForm.email.$touched"
class="error">Invalid email format.</div>
</div>

<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" ng-model="formData.phone"
pattern="[0-9]{10}" required>
<div ng-show="jobForm.phone.$error.required && jobForm.phone.
$touched" class="error">Phone Number is required.</div>
<div ng-show="jobForm.phone.$error.pattern && jobForm.phone.
$touched" class="error">Invalid phone number (10 digits).</div>
</div>

<div class="form-group">
<label for="jobTitle">Desired Job Title:</label>
<input type="text" id="jobTitle" name="jobTitle" ng-
model="formData.jobTitle" required>
<div ng-show="jobForm.jobTitle.$invalid && jobForm.jobTitle.
$touched" class="error">Desired Job Title is required.</div>
</div>

<div class="form-group">
<label for="experience">Years of Experience:</label>
<select id="experience" name="experience" ng-
model="formData.experience" required>
<option value="">-- Select --</option>
<option value="0">0 Years</option>
<option value="1">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3+ Years</option>
</select>
<div ng-show="jobForm.experience.$invalid && jobForm.experience.
$touched" class="error">Years of Experience is required.</div>
</div>

<div class="form-group">
<label for="skills">Key Skills:</label>
<textarea id="skills" name="skills" ng-model="formData.skills"
rows="4" required></textarea>
<div ng-show="jobForm.skills.$invalid && jobForm.skills.$touched"
class="error">Key Skills are required.</div>
</div>

<button type="submit" ng-disabled="jobForm.$invalid">Register</button>

<div ng-if="submissionMessage" class="success-


message">{{ submissionMessage }}</div>
</form>

<script>
angular.module('jobRegistrationApp', [])
.controller('JobRegistrationController', function($scope) {
$scope.formData = {};
$scope.submissionMessage = '';

$scope.submitForm = function() {
if ($scope.jobForm.$valid) {
// Process the form data (e.g., send to server)
console.log('Form Data:', $scope.formData);
$scope.submissionMessage = 'Registration successful!';
// Optionally reset the form
$scope.formData = {};
$scope.jobForm.$setPristine();
$scope.jobForm.$setUntouched();
} else {
console.log('Form is invalid. Please correct the
errors.');
$scope.submissionMessage = ''; // Clear success message
if there are errors
}
};
});
</script>

</body>
</html>

11. Write an angular JS application to access JSON file data of an


employee from a server using $http service.

HTML
<!DOCTYPE html>
<html ng-app="employeeApp">
<head>
<title>Employee Data</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<style>
body {
font-family: sans-serif;
}
.container {
width: 500px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
h2 {
text-align: center;
}
.employee-details {
margin-top: 20px;
border: 1px solid #eee;
padding: 15px;
border-radius: 3px;
}
.employee-details p {
margin: 5px 0;
}
.error {
color: red;
margin-top: 10px;
}
.loading {
font-style: italic;
color: gray;
}
</style>
</head>
<body ng-controller="EmployeeController">
<div class="container">
<h2>Employee Information</h2>

<button ng-click="fetchEmployeeData()">Fetch Employee Data</button>

<div ng-if="loading" class="loading">Loading employee data...</div>

<div ng-if="employee" class="employee-details">


<h3>{{ employee.name }}</h3>
<p><strong>ID:</strong> {{ employee.id }}</p>
<p><strong>Email:</strong> {{ employee.email }}</p>
<p><strong>Department:</strong> {{ employee.department }}</p>
<p><strong>Designation:</strong> {{ employee.designation }}</p>
</div>

<div ng-if="error" class="error">Error fetching data: {{ error }}</div>


</div>

<script>
angular.module('employeeApp', [])
.controller('EmployeeController', ['$scope', '$http',
function($scope, $http) {
$scope.employee = null;
$scope.error = null;
$scope.loading = false;

$scope.fetchEmployeeData = function() {
$scope.loading = true;
$scope.employee = null;
$scope.error = null;

// Replace 'your-api-endpoint.json' with the actual URL of


your JSON file on the server
$http.get('your-api-endpoint.json')
.then(function(response) {
$scope.employee = response.data;
$scope.loading = false;
})
.catch(function(error) {
$scope.error = error.statusText || 'An error
occurred while fetching data.';
$scope.loading = false;
});
};
}]);
</script>

</body>
</html>

12. Develop a web application to manage student information using


Express and Angular JS.

Project Structure:

student-management/
├── server/
│ ├── server.js
│ ├── routes/
│ │ └── students.js
│ └── models/
│ └── student.js
├── public/
│ ├── index.html
│ ├── app.js
│ ├── controllers/
│ │ └── studentController.js
│ ├── services/
│ │ └── studentService.js
│ └── css/
│ └── style.css
└── package.json

1. Backend (Express.js):

a) server/package.json:

JSON
{
"name": "student-management-server",
"version": "1.0.0",
"description": "Backend for student management app",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"mongoose": "^8.0.3"
},
"devDependencies": {
"nodemon": "^3.0.2"
}
}

Run npm install in the server directory.

b) server/models/student.js:

JavaScript
const mongoose = require('mongoose');

const studentSchema = new mongoose.Schema({


name: { type: String, required: true },
email: { type: String, required: true, unique: true },
major: String,
grade: Number
});

module.exports = mongoose.model('Student', studentSchema);

c) server/routes/students.js:

JavaScript
const express = require('express');
const router = express.Router();
const Student = require('../models/student');

// GET all students


router.get('/', async (req, res) => {
try {
const students = await Student.find();
res.json(students);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// GET a specific student by ID


router.get('/:id', async (req, res) => {
try {
const student = await Student.findById(req.params.id);
if (!student) {
return res.status(404).json({ message: 'Student not found' });
}
res.json(student);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// POST a new student


router.post('/', async (req, res) => {
const student = new Student({
name: req.body.name,
email: req.body.email,
major: req.body.major,
grade: req.body.grade
});

try {
const newStudent = await student.save();
res.status(201).json(newStudent);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// PUT (update) an existing student


router.put('/:id', async (req, res) => {
try {
const student = await Student.findById(req.params.id);
if (!student) {
return res.status(404).json({ message: 'Student not found' });
}
if (req.body.name) student.name = req.body.name;
if (req.body.email) student.email = req.body.email;
if (req.body.major) student.major = req.body.major;
if (req.body.grade) student.grade = req.body.grade;

const updatedStudent = await student.save();


res.json(updatedStudent);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// DELETE a student
router.delete('/:id', async (req, res) => {
try {
const student = await Student.findByIdAndDelete(req.params.id);
if (!student) {
return res.status(404).json({ message: 'Student not found' });
}
res.json({ message: 'Student deleted successfully' });
} catch (err) {
res.status(500).json({ message: err.message });
}
});

module.exports = router;

d) server/server.js:

JavaScript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const studentRoutes = require('./routes/students');

const app = express();


const port = 3000;

app.use(cors());
app.use(bodyParser.json());
app.use('/api/students', studentRoutes);

// MongoDB Connection
mongoose.connect('mongodb://127.0.0.1:27017/studentDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});

app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

2. Frontend (AngularJS):

a) public/index.html:

<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<title>Student Management</title>
<link rel="stylesheet" href="css/style.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<script src="app.js"></script>
<script src="controllers/studentController.js"></script>
<script src="services/studentService.js"></script>
</head>
<body>
<div ng-controller="StudentController">
<h1>Student Management</h1>

<div>
<h2>Add New Student</h2>
<form ng-submit="addStudent()">
<label for="name">Name:</label>
<input type="text" id="name" ng-model="newStudent.name"
required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" ng-model="newStudent.email"
required><br><br>

<label for="major">Major:</label>
<input type="text" id="major" ng-model="newStudent.major"><br><br>

<label for="grade">Grade:</label>
<input type="number" id="grade" ng-model="newStudent.grade"><br><br>

<button type="submit">Add Student</button>


</form>
<div ng-if="addError" class="error">{{ addError }}</div>
<div ng-if="addSuccess" class="success">{{ addSuccess }}</div>
</div>

<hr>

<div>
<h2>Student List</h2>
<ul ng-if="students.length > 0">
<li ng-repeat="student in students">
{{ student.name }} ({{ student.email }}) - Major: {{ student.major ||
'N/A' }}, Grade: {{ student.grade || 'N/A' }}
<button ng-click="editStudent(student._id)">Edit</button>
<button ng-click="deleteStudent(student._id)">Delete</button>
</li>
</ul>
<p ng-if="students.length === 0">No students found.</p>
<div ng-if="fetchError" class="error">{{ fetchError }}</div>
</div>

<hr>

<div ng-if="editingStudent">
<h2>Edit Student</h2>
<form ng-submit="updateStudent()">
<label for="editName">Name:</label>
<input type="text" id="editName" ng-model="editingStudent.name"
required><br><br>

<label for="editEmail">Email:</label>
<input type="email" id="editEmail" ng-model="editingStudent.email"
required><br><br>

<label for="editMajor">Major:</label>
<input type="text" id="editMajor" ng-
model="editingStudent.major"><br><br>

<label for="editGrade">Grade:</label>
<input type="number" id="editGrade" ng-
model="editingStudent.grade"><br><br>

<button type="submit">Update Student</button>


<button ng-click="cancelEdit()">Cancel</button>
</form>
<div ng-if="updateError" class="error">{{ updateError }}</div>
<div ng-if="updateSuccess" class="success">{{ updateSuccess }}</div>
</div>
</div>
</body>
</html>

b) public/app.js:

JavaScript
angular.module('studentApp', []);

c) public/controllers/studentController.js:

JavaScript
angular.module('studentApp')
.controller('StudentController', ['$scope', 'StudentService', function($scope,
StudentService) {
$scope.students = [];
$scope.newStudent = {};
$scope.editingStudent = null;
$scope.addError = null;
$scope.addSuccess = null;
$scope.fetchError = null;
$scope.updateError = null;
$scope.updateSuccess = null;

// Fetch all students


$scope.fetchStudents = function() {
StudentService.getStudents()
.then(function(response) {
$scope.students = response.data;
$scope.fetchError = null;
})
.catch(function(error) {
$scope.fetchError = 'Error fetching students: ' + error.data.message
|| error.statusText;
$scope.students = [];
});
};

$scope.fetchStudents(); // Load students on page load

// Add a new student


$scope.addStudent = function() {
$scope.addError = null;
$scope.addSuccess = null;
StudentService.addStudent($scope.newStudent)
.then(function(response) {
$scope.students.push(response.data);
$scope.newStudent = {}; // Clear the form
$scope.addSuccess = 'Student added successfully!';
})
.catch(function(error) {
$scope.addError = 'Error adding student: ' + error.data.message ||
error.statusText;
});
};

// Edit a student
$scope.editStudent = function(id) {
$scope.updateError = null;
$scope.updateSuccess = null;
StudentService.getStudent(id)
.then(function(response) {
$scope.editingStudent = angular.copy(response.data); // Create a copy
to avoid direct modification
})
.catch(function(error) {
console.error('Error fetching student for edit:', error);
$scope.updateError = 'Error fetching student details.';
});
};

// Update a student
$scope.updateStudent = function() {
$scope.updateError = null;
$scope.updateSuccess = null;
StudentService.updateStudent($scope.editingStudent._id,
$scope.editingStudent)
.then(function(response) {
const index = $scope.students.findIndex(student => student._id ===
response.data._id);
if (index !== -1) {
$scope.students[index] = response.data;
}
$scope.editingStudent = null; // Hide edit form
$scope.updateSuccess = 'Student updated successfully!';
})
.catch(function(error) {
$scope.updateError = 'Error updating student: ' + error.data.message
|| error.statusText;
});
};

// Cancel edit
$scope.cancelEdit = function() {
$scope.editingStudent = null;
};

// Delete a student
$scope.deleteStudent = function(id) {
if (confirm('Are you sure you want to delete this student?')) {
StudentService.deleteStudent(id)
.then(function(response) {
$scope.students = $scope.students.filter(student => student._id !==
id);
})
.catch(function(error) {
console.error('Error deleting student:', error);
});
}
};
}]);

d) public/services/studentService.js:

JavaScript
angular.module('studentApp')
.service('StudentService', ['$http', function($http) {
const baseUrl = '/api/students';

this.getStudents = function() {
return $http.get(baseUrl);
};

this.getStudent = function(id) {
return $http.get(baseUrl + '/' + id);
};

this.addStudent = function(studentData) {
return $http.post(baseUrl, studentData);
};

this.updateStudent = function(id, studentData) {


return $http.put(baseUrl + '/' + id, studentData);
};

this.deleteStudent = function(id) {
return $http.delete(baseUrl + '/' + id);
};
}]);

e) public/css/style.css:

CSS
body {
font-family: sans-serif;
margin: 20px;
}

.error {
color: red;
margin-top: 5px;
}

.success {
color: green;
margin-top: 5px;
}

label {
display: inline-block;
width: 100px;
text-align: right;
margin-right: 10px;
}

input[type="text"],
input[type="email"],
input[type="number"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 200px;
}

button {
padding: 8px 15px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-right: 5px;
}

button:hover {
background-color: #0056b3;
}

ul {
list-style-type: none;
padding: 0;
}

li {
padding: 8px 0;
border-bottom: 1px solid #eee;
}

li:last-child {
border-bottom: none;
}

How to Run the Application:

1. Navigate to the server directory in your terminal and run:

Bash

npm install
npm start

This will start the Express.js backend server on port 3000. Make sure you have MongoDB
running on mongodb://127.0.0.1:27017.
2. Navigate to the student-management directory (the root of your project) and open the
public/index.html file in your web browser.

13. Write a program to create a simple calculator Application using


React JS.

Src/App.js

import React, { useState } from "react";


import "./App.css";
function App() {
const [input, setInput] = useState("");
const handleButtonClick = (value) => {
if (value === "=") {
try {
setInput(eval(input).toString()); // Caution: Avoid `eval` in production apps.
} catch (error) {
setInput("Error");
}
} else if (value === "C") {
setInput("");
} else {
setInput(input + value);
}
};
return (
<div className="App">
<h1>React Calculator</h1>
<div className="calculator">
<div className="display">{input || "0"}</div>
<div className="buttons">
{["7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "C",
"+"].map((btn) => (
<button key={btn} onClick={() => handleButtonClick(btn)}>
{btn}
</button>
))}
<button className="equals" onClick={() => handleButtonClick("=")}>
=
</button>
</div>
</div>
</div>
);
}
export default App;

Src/App.css

.App {
text-align: center;
font-family: Arial, sans-serif;
}
.calculator {
display: inline-block;
background: #f0f0f0;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
.display {
width: 200px;
height: 40px;
margin-bottom: 10px;
background: #fff;
text-align: right;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 18px;
overflow-x: auto;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 50px);
gap: 10px;
}
button {
width: 50px;
height: 50px;
font-size: 18px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
.equals {
grid-column: span 4;
background: #28a745;
}
.equals:hover {
background: #1e7e34;
}

output :
14. Write a program to create a voting application using React JS
Src/App.js

import React, { useState } from "react";


import "./App.css";
function App() {
const [candidates, setCandidates] = useState([
{ name: "CSE1", votes: 0 },
{ name: "CSE2", votes: 0 },
{ name: "CSE3", votes: 0 },
]);
const handleVote = (index) => {
const updatedCandidates = [...candidates];
updatedCandidates[index].votes += 1;
setCandidates(updatedCandidates);
};
const resetVotes = () => {
const resetCandidates = candidates.map((candidate) => ({
...candidate,
votes: 0,
}));
setCandidates(resetCandidates);
};
return (
<div className="App">
<h1>Voting Application</h1>
<div className="candidates">
{candidates.map((candidate, index) => (
<div key={index} className="candidate">
<span>{candidate.name}</span>
<span>{candidate.votes} votes</span>
<button onClick={() => handleVote(index)}>Vote</button>
</div>
))}
</div>
<button className="reset" onClick={resetVotes}>
Reset Votes
</button>
</div>
);
}
export default App;

Src/App.css
.App {
text-align: center;
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
margin-bottom: 20px;
font-size: 2em;
}
.candidates {
display: flex;
flex-direction: column;
gap: 10px;
align-items: center;
}
.candidate {
display: flex;
justify-content: space-between;
align-items: center;
width: 300px;
padding: 10px;
background: #f9f9f9;
border: 1px solid #ddd;
border-radius: 5px;
}
.candidate button {
padding: 5px 10px;
background: #007bff;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
transition: background 0.3s;
}
.candidate button:hover {
background: #0056b3;
}
.reset {
margin-top: 20px;
padding: 10px 20px;
background: #dc3545;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
.reset:hover {
background: #c82333;
}

output :
15. Develop a leave management system for an organization where users can
apply different types of leaves such as casual leave and medical leave. They
also can view the available number of days using react application.

Src/App.js

import React, { useState } from "react";


import "./App.css";
function App() {
const initialLeaveBalance = {
CasualLeave: 12,
MedicalLeave: 10,
EarnedLeave: 8,
};
const [leaveBalance, setLeaveBalance] = useState(initialLeaveBalance);
const [leaveHistory, setLeaveHistory] = useState([]);
const [selectedLeaveType, setSelectedLeaveType] = useState("CasualLeave");
const [leaveDays, setLeaveDays] = useState(1);
const handleApplyLeave = () => {
if (leaveDays < 1 || isNaN(leaveDays)) {
alert("Please enter a valid number of days.");
return;
}
if (leaveBalance[selectedLeaveType] >= leaveDays) {
// Update leave balance
setLeaveBalance({
...leaveBalance,
[selectedLeaveType]: leaveBalance[selectedLeaveType] - leaveDays,
});
// Add to leave history
setLeaveHistory([
...leaveHistory,
{
type: selectedLeaveType,
days: leaveDays,
date: new Date().toLocaleDateString(),
},
]);
alert("Leave applied successfully!");
} else {
alert("Not enough leave balance!");
}
};
const handleResetLeaves = () => {
setLeaveBalance(initialLeaveBalance);
setLeaveHistory([]);
};
return (
<div className="App">
<h1>Leave Management System</h1>
<div className="leave-balance">
<h2>Leave Balance</h2>
<ul>
{Object.entries(leaveBalance).map(([type, days]) => (
<li key={type}>
{type}: {days} days
</li>
))}
</ul>
</div>
<div className="apply-leave">
<h2>Apply Leave</h2>
<label>
Leave Type:
<select
value={selectedLeaveType}
onChange={(e) => setSelectedLeaveType(e.target.value)}
>
{Object.keys(leaveBalance).map((type) => (
<option key={type} value={type}>
{type}
</option>
))}
</select>
</label>
<label>
Number of Days:
<input
type="number"
min="1"
value={leaveDays}
onChange={(e) => setLeaveDays(parseInt(e.target.value))}
/>
</label>
<button onClick={handleApplyLeave}>Apply Leave</button>
</div>
<div className="leave-history">
<h2>Leave History</h2>
{leaveHistory.length > 0 ? (
<ul>
{leaveHistory.map((leave, index) => (
<li key={index}>
{leave.type}: {leave.days} day(s) on {leave.date}
</li>
))}
</ul>
):(
<p>No leave history available.</p>
)}
</div>
<button className="reset-button" onClick={handleResetLeaves}>
Reset Leave Balances
</button>
</div>
);
}
export default App;

Src/App.css

.App {
text-align: center;
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
font-size: 2em;
margin-bottom: 20px;
}
.leave-balance,
.apply-leave,
.leave-history {
margin: 20px 0;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
}
h2 {
margin-bottom: 10px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 5px 0;
}
label {
display: block;
margin: 10px 0;
}
input,
select {
margin-left: 10px;
padding: 5px;
font-size: 16px;
}
button {
margin-top: 10px;
padding: 10px 15px;
font-size: 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background-color: #0056b3;
}
.reset-button {
background-color: #dc3545;
}
.reset-button:hover {
background-color: #c82333;
}

output :
16. Build a music store application using react components and provide routing
among the web pages.

Src/app.js

import React from 'react';


import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Header from './Header';
import Footer from './Footer';
import Home from './Home';
import Store from './Store';
import About from './About';
import NotFound from './NotFound';
const App = () => (
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/store" element={<Store />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
<Footer />
</Router>
);
export default App;
Src/Header.js
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => (
<header>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/store">Store</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
</header>
);
export default Header;
Src/Footer.js
import React from 'react';
const Footer = () => (
<footer>
<p>&copy; 2024 Music Store</p>
</footer>
);
export default Footer;
Src/Home.js
import React from 'react';
const Home = () => (
<main>
<h1>Welcome to the Music Store</h1>
<p>Your one-stop shop for musical instruments and gear!</p>
</main>
);
export default Home;
Src/Store.js
import React from 'react';
const Store = () => {
const products = [
{ id: 1, name: 'Acoustic Guitar', price: '$200' },
{ id: 2, name: 'Electric Guitar', price: '$400' },
{ id: 3, name: 'Drum Set', price: '$600' },
];
return (
<main>
<h1>Store</h1>
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} - {product.price}
</li>
))}
</ul>
</main>
);
};
export default Store;

Src/About.js
import React from 'react';
const About = () => (
<main>
<h1>About Us</h1>
<p>We are passionate about music and dedicated to serving musicians
worldwide.</p>
</main>
);
export default About;

Src/NotFound.js
import React from 'react';
const NotFound = () => (
<main>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</main>
);
export default NotFound;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

src/index.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header nav ul {
display: flex;

list-style: none;
background-color: #333;
padding: 0;
margin: 0;
}
header nav ul li {
margin: 0;
}
header nav ul li a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: block;
}
header nav ul li a:hover {
background-color: #575757;
}
footer {
text-align: center;
background: #333;
color: white;
padding: 10px 0;
position: fixed;
bottom: 0;
width: 100%;
}
main {
padding: 20px;
}

output :
17. Create a react application for an online store which consist of registration,
login, product information pages and implement routing to navigate through
these pages.

Structure:
src/
├── components/
│ ├── Header.js
│ ├── Footer.js
│ ├── Home.js
│ ├── Login.js
│ ├── Register.js
│ ├── Product.js
│ ├── NotFound.js
├── App.js
├── index.js
components/ Header.js
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => (
<header>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Login</Link></li>
<li><Link to="/register">Register</Link></li>
<li><Link to="/product">Product</Link></li>
</ul>
</nav>
</header>
);
export default Header;
components/ Footer.js
import React from 'react';
const Footer = () => (
<footer>
<p>&copy; 2024 Online Store</p>
</footer>
);
export default Footer;

components/ Home.js
import React from 'react';
const Home = () => (
<main>
<h1>Welcome to the Online Store</h1>
<p>Shop the best products here!</p>
</main>
);
export default Home;
components/ Login.js
import React, { useState } from 'react';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Logged in with email: ${email}`);
};
return (
<main>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={(e) =>
setEmail(e.target.value)}
required />
</label>
<br />
<label>
Password:
<input type="password" value={password} onChange={(e) =>
setPassword(e.target.value)} required />
</label>
<br />
<button type="submit">Login</button>
</form>
</main>
);
};
export default Login;
components/ Register.js
import React, { useState } from 'react';
const Register = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Registered: ${formData.name} (${formData.email})`);
};
return (
<main>
<h1>Register</h1>
<form onSubmit={handleSubmit}>
<label>
Name:
<input name="name" type="text" value={formData.name}
onChange={handleChange} required />
</label>
<br />
<label>
Email:
<input name="email" type="email" value={formData.email}
onChange={handleChange} required />
</label>
<br />
<label>
Password:
<input name="password" type="password" value={formData.password}
onChange={handleChange} required />
</label>
<br />
<button type="submit">Register</button>
</form>
</main>
);
};
export default Register;
components/ Product.js
import React from 'react';
const Product = () => {
const products = [
{ id: 1, name: 'Laptop', price: '$1000', description: 'High-performance laptop.' },
{ id: 2, name: 'Headphones', price: '$200', description: 'Noise-cancelling
headphones.' },
{ id: 3, name: 'Smartphone', price: '$800', description: 'Latest-gen
smartphone.' },
];
return (
<main>
<h1>Products</h1>
<ul>
{products.map((product) => (
<li key={product.id}>
<h2>{product.name}</h2>
<p>{product.description}</p>
<p>Price: {product.price}</p>
</li>
))}
</ul>
</main>
);
};
export default Product
components/ NotFound.js
import React from 'react';
const NotFound = () => (
<main>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</main>
);
export default NotFound;
App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './components/Home';
import Login from './components/Login';
import Register from './components/Register';
import Product from './components/Product';
import NotFound from './components/NotFound';
const App = () => (
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/product" element={<Product />} />
<Route path="*" element={<NotFound />} />
</Routes>
<Footer />
</Router>
);
export default App;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

output:

You might also like