0% found this document useful (0 votes)
23 views50 pages

FSWD LAB

fswd

Uploaded by

viji99174
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)
23 views50 pages

FSWD LAB

fswd

Uploaded by

viji99174
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/ 50

EX:NO:1 Develop a portfolio website for yourself which gives details about yourself for a

potential recruiter.

AIM:

To develop a portfolio website which gives details about yourself for a potential recruiter.

ALGORITHM

Step 1: Set Up React Project Make sure you have Node.js and npm (Node Package Manager)
installed on your computer. If not, you can download them from the official Node.js website.

Step 2: Create a folder structure inside the "src" folder, like src : App.js ,styles.css , index.js,
components : Header.js ,About.js, Projects.js, Contact.js.
Step 3: Let's implement the basic components like header.js, about.js, project.js, etc.,

Step 4: Styling can create a styles.css file to style your components further. Customize it
according to your design preferences.

Step 5: Run Your Portfolio Website Start the development server again using npm start in your
project's root folder. Your portfolio website should now be accessible with the basic content
you've added to the components.

CODING

To create a new React project, open your terminal (command prompt) and run the following
commands:

npx create-react-app portfolio-website


cd portfolio- website
npm start

Header.js: This component will contain the header section of your portfolio website.
// Header.js
import React from
'react';

const Header = () => {


return (
<header>
<h1>Your Name</h1>
<p>Web Developer</p>
</header>
);
};

export default Header;

About.js: This component will display information about yourself.

// About.js
import React from
'react';
const About = () => {
return (
<section id="about">
<h2>About Me</h2>

<p>
Write a short paragraph about yourself, your skills, and your passions.

</p>
</section>
);

};
export default About;
Projects.js: This component will showcase your projects.
// Projects.js
import React from
'react';
const Projects = () =>
{ return (
<section>

<h2>Projects</h2>
{/* Add your project details here */}
</section>
);
};
export default Projects';
Contact.js: This component will provide your contact information.

// Contact.js
import React from
'react';
const Contact = () => {
return (
<section id="contact">

<h2>Contact Me</h2>
<p>Email: [email protected]</p>
<p>LinkedIn: linkedin.com/in/yourprofile</p>

<p>GitHub: github.com/yourusername</p>
</section>

);
};
export default Contact;

App.js: This is the main component that will bring together all the other
components.
import React from 'react';
import './styles.css';
import Header from './components/Header';
import About from './components/About';
import Projects from './components/Projects';
import Contact from './components/Contact'; function App() {
return (
<div className="App">

<Header />
<main>

<About />
<Projects />

<Contact />
</main>
</div>
);

export default App;

styles.css
.App {
text-align:
center;padding:
20px;
}

header {
background-color:
#333;color: #fff;
padding: 20px;

}
main {

margin-top: 20px;

h2 {
margin-bottom: 10px;

p{
margin-bottom: 5px;

img {
max-width: 200px;
border-radius: 50%;

Index.js
import React from 'react';
import ReactDOM from 'react dom';
import App from './App';
import reportWebVitals from
'./reportWebVitals';
ReactDOM.render(
<React.StrictMode>

<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();

OUTPUT

RESULT:
Thus the portfolio website is developed which gives details about yourself for a potential
recruiter
EX:NO:2 Create a web application to manage the TO-DO list of users, where users can
login and manage their to-do items

AIM: To create a web application to manage the TO-DO list of users, where users can login and
manage their to-do items

ALGORITHM

Step 1: Set Up Your React App:


First, make sure you have Node.js and npm installed. Then, create a new React app:

Step 2: FOLDER STRUCTURE

Step 3:
Write the program code in App.js file in the src directory

Step 4:
Run the application, type the following command in the terminal:
npm start
Type the following URL in the browser:
http://localhost:3000/
CODING

App.js
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Button from "react-bootstrap/Button";
import InputGroup from "react-bootstrap/InputGroup";
import FormControl from "react-bootstrap/FormControl";
import ListGroup from "react-bootstrap/ListGroup";
class App extends Component {
constructor(props) {
super(props);

// Setting up state
this.state = {
userInput: "",
list: [],
};}
// Set a user input value
updateInput(value) {
this.setState({
userInput: value,
});}
// Add item if user input in not empty
addItem() {
if (this.state.userInput !== "") {
const userInput = {
// Add a random id which is used to delete
id: Math.random(),
// Add a user value to list
value: this.state.userInput,};
// Update list
const list = [...this.state.list];
list.push(userInput);
// reset state
this.setState({
list,
userInput: "",});}}
// Function to delete item from list use id to delete
deleteItem(key) {
const list = [...this.state.list];
// Filter values and leave value which we need to delete
const updateList = list.filter((item) => item.id !== key);
// Update list in state
this.setState({
list: updateList,
});}
editItem = (index) => {
const todos = [...this.state.list];
const editedTodo = prompt('Edit the todo:');
if (editedTodo !== null && editedTodo.trim() !== '') {
let updatedTodos = [...todos]
updatedTodos[index].value= editedTodo
this.setState({
list: updatedTodos,
});
}
}
render()
{return (
<Container>
<Row
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
fontSize: "3rem",
fontWeight: "bolder",
}}>
TODO LIST
</Row>
<hr />
<Row>
<Col md={{ span: 5, offset: 4 }}>
<InputGroup className="mb-3">
<FormControl
placeholder="add item . . . "
size="lg"
value={this.state.userInput}
onChange={(item) =>this.updateInput(item.target.value)}
aria-label="add something"
aria-describedby="basic-addon2"
/>
<InputGroup>
<Button
variant="dark"
className="mt-2"
onClick={() => this.addItem()}>
ADD
</Button>
</InputGroup>
</InputGroup>
</Col>
</Row>
<Row>
<Col md={{ span: 5, offset: 4 }}>
<ListGroup>
{/* map over and print items */}
{this.state.list.map((item, index) => {
return (
<div key = {index} >
<ListGroup.Item
variant="dark"
action
style={{display:"flex",justifyContent:'space-between'}}>
{item.value}
<span>
<Button style={{marginRight:"10px"}}
variant = "light"
onClick={() => this.deleteItem(item.id)}>
Delete
</Button>
<Button variant = "light"
onClick={() => this.editItem(index)}>
Edit
</Button>
</span>
</ListGroup.Item>
</div>
);})}
</ListGroup>
</Col>
</Row>
</Container>
);
}}
export default App;
OUTPUT
RESULT:

Thus the web application to manage the TO-DO list of users, where users can login and
manage their to-do items are created successfully.
EX:NO:3 Create a simple micro blogging application (like twitter) that allows people to post
their content which can be viewed by people who follow them.

AIM
To create a simple micro blogging application (like twitter) that allows people to post their
content which can be viewed by people who follow them.

ALGORITHM

STEP 1: Setting Up the Project,Create a new directory for your project and set up the backend and
frontend separately.
Backend (Node.js and Express.js):
mkdir microblog-backend
cd microblog-backend

npm init -y

npm install express mongoose body-parser cors


Frontend (React.js):
mkdir microblog-frontend

cd microblog-frontend

npx create-react-app .

STEP 2: In the microblog-backend directory, create a file named server.js and implement the
Express.js server.

STEP 3: In the microblog-frontend directory, open the src/App.js file and replace its content
with the App.js code.

STEP 4: Create a basic CSS file to style the app. We can create a App.css file in the src folder of
your frontend project and add styles for the application.

STEP 5: For Running the Application,


Start both the backend and frontend servers:

 In the microblog-backend directory, run: node server.js

 In the microblog-frontend directory, run: npm start

Now the microblogging application should be running. We can access it at http://localhost:3000


by default.
CODING:

Server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(bodyParser.json());
// MongoDB setup (create a MongoDB Atlas cluster and replace the URI)
const mongoURI = 'YOUR_MONGODB_URI';
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// Define Mongoose schema and models for Posts
const PostSchema = new mongoose.Schema({
text: String,
author: String,
timestamp: { type: Date, default: Date.now }
});
const Post = mongoose.model('Post', PostSchema);
// API endpoints for CRUD operations
app.get('/api/posts', (req, res) => {
Post.find().sort({ timestamp: -1 })
.then(posts => res.json(posts))
.catch(err => res.status(400).json('Error: ' + err));
});
app.post('/api/posts', (req, res) => {
const { text, author } = req.body;
const newPost = new Post({ text, author });
newPost.save()
.then(() => res.json('Post added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

APP.JS
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [posts, setPosts] = useState([]);
const [text, setText] = useState('');
const [author, setAuthor] = useState('');
useEffect(() => {
fetch('/api/posts')
.then(res => res.json())
.then(data => setPosts(data))
.catch(err => console.error('Error fetching data: ', err));
}, []);
const handlePostSubmit = () => {
if (text && author) {
fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, author }),
})
.then(() => {
setText('');
setAuthor('');
fetch('/api/posts')
.then(res => res.json())
.then(data => setPosts(data))
.catch(err => console.error('Error fetching data: ', err));
})
.catch(err => console.error('Error posting data: ', err));
}
};
return (
<div className="App">
<h1>Microblogging App</h1>
<div>
<input
type="text"
placeholder="Your name"
value={author}
onChange={e => setAuthor(e.target.value)}
/>
<textarea
placeholder="What's on your mind?"
value={text}
onChange={e => setText(e.target.value)}
></textarea>
<button onClick={handlePostSubmit}>Post</button>
</div>
<div className="posts">
{posts.map(post => (
<div className="post" key={post._id}>
<p>{post.text}</p>
<p>Author: {post.author}</p>
</div>
))}
</div>
</div>
);
}export default App;

App.css

.App {
text-align: center;
margin: 20px;
}
input,
textarea,
button {
display: block;
margin: 10px auto;
}
.posts {
display: flex;
flex-direction: column;
align-items: center;
}
.post {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
max-width: 400px;
}

OUTPUT
RESULT:
Thus the simple micro blogging application is created successfully that allows people to
post their content which can be viewed by people who follow them are created successfully.
EX:NO:4 Create a food delivery website where users can order food from a particular
restaurant listed in the website.

AIM : To create a food delivery website where users can order food from a particular restaurant
listed in the website.

ALGORITHM

Step 1. Set Up Your React App:

First, make sure you have Node.js and npm installed. Then, create a new React app:
npx create-react-app food-delivery-app
cd food-delivery-app
npm start

Step 2. Inside the src directory, open the index.js file and App.js file,set up your app's rendering:

Step 3. For Create Components move to the src directory, create a components directory and
update the necessary components inside it.

Step 4.Run the application, now food delivery home page is opened from that select a restaurant
from the list and navigate to its menu, you'll be able to add items to the cart.

Step 5. Then, when you navigate to the cart and click "Place Order," the selected items will be
logged to the console and the cart will be reset.

CODING

Index.js

import React from 'react';


import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React, { useState } from 'react';


import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import RestaurantList from './components/RestaurantList';
import RestaurantMenu from './components/RestaurantMenu';
import Cart from './components/Cart';
function App() {
const [cartItems, setCartItems] = useState([]);
const addToCart = (item) => {
// Placeholder: Add logic to update cart items
};
const placeOrder = () => {
// Placeholder: Add logic to place order
};
return (
<Router>
<div>
<Switch>
<Route exact path="/" component={RestaurantList} />
<Route path="/restaurants/:id/menu" render={(props) => <RestaurantMenu {...props}
addToCart={addToCart} />} />
<Route path="/cart" render={() => <Cart cartItems={cartItems} placeOrder={placeOrder}
/>} />
</Switch>
</div>
</Router>
);
}
export default App;

RestaurantList.js

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


import axios from 'axios';
import { Link } from 'react-router-dom';
function RestaurantList() {
const [restaurants, setRestaurants] = useState([]);
useEffect(() => {
axios.get('http://localhost:5000/api/restaurants')
.then(response => {
setRestaurants(response.data);
})
.catch(error => {
console.error('Error fetching restaurants:', error);
});
}, []);
return (
<div>
<h1>Restaurant List</h1>
<ul>
{restaurants.map(restaurant => (
<li key={restaurant._id}>
<h2>{restaurant.name}</h2>
<Link to={`/restaurants/${restaurant._id}/menu`}>View Menu</Link>
</li>
))}
</ul>
</div>
);
}
export default RestaurantList;
RestaurantMenu.js

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


import axios from 'axios';
import { useParams } from 'react-router-dom';
function RestaurantMenu() {
const { id } = useParams();
const [menu, setMenu] = useState([]);
useEffect(() => {
axios.get(`http://localhost:5000/api/restaurants/${id}/menu`)
.then(response => {
setMenu(response.data);
})
.catch(error => {
console.error('Error fetching menu:', error);
});
}, [id]);
return (
<div>
<h2>Menu</h2>
<ul>
{menu.map(item => (
<li key={item._id}>
<span>{item.name}</span>
<span>{item.price}</span>
<button>Add to Cart</button>
</li>
))}
</ul>
</div>
);}
export default RestaurantMenu;

Cart.js

import React from 'react';


function Cart() {
// Implement cart functionality here
return (
<div>
<h2>Cart</h2>
{/* Display cart items */}
<button>Place Order</button>
</div>
);
}
export default Cart;
OUTPUT

Homepage :
Displays a list of restaurants fetched from the server.

/*
Restaurant List

- restaurant1
- View Menu

- restaurant2
- View Menu

- restaurant3
- View Menu
*/

// Clicking on the "View Menu" link for a restaurant navigates to the menu page
("/restaurants/:id/menu"):

// Menu Page ("/restaurants/:id/menu"):


// - Displays the menu of the selected restaurant based on the `id` parameter from the URL.

/*
Menu

- Item 1
- Price: $10.99
- Add to Cart

- Item 2
- Price: $8.99
- Add to Cart

- Item 3
- Price: $12.99
- Add to Cart
*/

// Clicking on the "Add to Cart" button on the menu page adds the corresponding item to
the cart:

// Cart Page ("/cart"):


// - Displays the items added to the cart.

/*
Cart

- Item 1
- Price: $10.99

- Item 2
- Price: $8.99

- Item 3
- Price: $12.99

Place Order Button


*/

// Clicking on the "Place Order" button on the cart page triggers the placeOrder function.

RESULT:
Thus the food delivery website where users can order food from a particular restaurant
listed in the website are created successfully.
EX:NO:5 Develop a classifieds web application to buy and sell used products.

AIM : To develop a classifieds web application to buy and sell used products.

ALGORITHM

Backend (Node.js and Express):

Step 1: Set up a Node.js project with Express.


Step 2: Connect to MongoDB using Mongoose.
Step 3: Create a Product schema to represent classified items.
Step 4: Implement API endpoints for:
 Fetching all products.
 Adding a new product.
Step5: Handle CORS for cross-origin requests.

Frontend (React):

Step 6: Create a React app using create-react-app.


Step 7: Use axios for making API requests to the backend.
Step 8: Implement components for displaying a list of products and adding a new product.
Step 8: Manage state using useState and useEffect.
Step 9: Set up routes using react-router-dom for different pages.

CODING

server.js

const express = require('express');


const mongoose = require('mongoose');
const cors = require('cors');

const app = express();


const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/classifieds', { 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');
});
const productSchema = new mongoose.Schema({
title: String,
description: String,
price: Number,
});

const Product = mongoose.model('Product', productSchema);

app.get('/api/products', async (req, res) => {


try {
const products = await Product.find();
res.json(products);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

app.post('/api/products', async (req, res) => {


const { title, description, price } = req.body;
const product = new Product({ title, description, price });

try {
await product.save();
res.json({ message: 'Product added successfully' });
} catch (error) {
console.error('Error adding product:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

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

src/App.js

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


import axios from 'axios';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function Home() {
const [products, setProducts] = useState([]);

useEffect(() => {
axios.get('http://localhost:5000/api/products')
.then(response => setProducts(response.data))
.catch(error => console.error('Error fetching products:', error));
}, []);
return (
<div>
<h2>Products</h2>
<ul>
{products.map(product => (
<li key={product._id}>
<strong>{product.title}</strong> - ${product.price}
<p>{product.description}</p>
</li>
))}
</ul>
</div>
);
}

function AddProduct() {
const [newProduct, setNewProduct] = useState({ title: '', description: '', price: '' });

const handleInputChange = (e) => {


const { name, value } = e.target;
setNewProduct({ ...newProduct, [name]: value });
};

const handleAddProduct = () => {


axios.post('http://localhost:5000/api/products', newProduct)
.then(response => {
console.log(response.data);
setNewProduct({ title: '', description: '', price: '' });
})
.catch(error => console.error('Error adding product:', error));
};

return (
<div>
<h2>Add Product</h2>
<label>Title: <input type="text" name="title" value={newProduct.title}
onChange={handleInputChange} /></label>
<label>Description: <input type="text" name="description" value={newProduct.description}
onChange={handleInputChange} /></label>
<label>Price: <input type="number" name="price" value={newProduct.price}
onChange={handleInputChange} /></label>
<button onClick={handleAddProduct}>Add Product</button>
</div>
);
}

function App() {
return (
<Router>
<div>
<h1>Classifieds Web Application</h1>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/add">Add Product</Link></li>
</ul>
</nav>
<hr />
<Route exact path="/" component={Home} />
<Route path="/add" component={AddProduct} />
</div>
</Router>
);
}

export default App;

OUTPUT

This output template provides a basic structure for the frontend application:

Homepage ("/"):
 Displays a list of products fetched from the server.
 Each product is displayed with its title, price, and description.

Classifieds Web Application

Products

- Product 1
- Title: [Product Title]
- Price: $[Product Price]
- Description: [Product Description]

- Product 2
- Title: [Product Title]
- Price: $[Product Price]
- Description: [Product Description]

Add Product

- Title: [Input Field]


- Description: [Input Field]
- Price: [Input Field]
- [Add Product Button]
*/

Login Page
RESULT:
Thus a classifieds web application to buy and sell used products are created successfully.
EX:NO:6 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.

AIM : To 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.

ALGORITHM

Backend (Node.js and Express):


 Set up a Node.js project with Express.
 Connect to MongoDB using Mongoose.
 Create a User schema to represent employees.
 Create a Leave schema to represent leave applications.
 Implement API endpoints for:
 User registration and login.
 Applying for different types of leaves (e.g., casual leave, medical leave).
 Viewing available leave balance.
 Fetching leave applications.
 Handle user authentication for protected routes.
Frontend (React):
 Create a React app using create-react-app.
 Use axios for making API requests to the backend.
 Implement components for user registration, login, applying for leaves, viewing
leave balance, and fetching leave applications.
 Manage state using useState and useEffect.
 Set up routes using react-router-dom for different pages.
 Implement a dashboard to show the available leave balance.
 Display a list of leave applications.

CODING

server.js

const express = require('express');


const mongoose = require('mongoose');
const cors = require('cors');

const app = express();


const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/leave-management', { 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');
});

const userSchema = new mongoose.Schema({


username: String,
password: String,
leaveBalance: {
casualLeave: { type: Number, default: 10 },
medicalLeave: { type: Number, default: 10 },
},
});

const User = mongoose.model('User', userSchema);

const leaveSchema = new mongoose.Schema({


userId: mongoose.Schema.Types.ObjectId,
leaveType: String,
startDate: Date,
endDate: Date,
});

const Leave = mongoose.model('Leave', leaveSchema);

// API Endpoints

// User registration
app.post('/api/register', async (req, res) => {
const { username, password } = req.body;
const newUser = new User({ username, password });
try {
await newUser.save();
res.json({ message: 'User registered successfully' });
} catch (error) {
console.error('Error registering user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

// User login
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username, password });
if (user) {
res.json({ message: 'Login successful', userId: user._id });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
} catch (error) {
console.error('Error logging in:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

// Apply for leave


app.post('/api/apply-leave', async (req, res) => {
const { userId, leaveType, startDate, endDate } = req.body;
const newLeave = new Leave({ userId, leaveType, startDate, endDate });
try {
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}

// Check available leave balance


if (user.leaveBalance[leaveType] > 0) {
// Deduct leave balance
user.leaveBalance[leaveType]--;
await user.save();
// Save leave application
await newLeave.save();
res.json({ message: 'Leave applied successfully' });
} else {
res.status(400).json({ error: 'Insufficient leave balance' });
}
} catch (error) {
console.error('Error applying leave:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

// Get leave balance


app.get('/api/leave-balance/:userId', async (req, res) => {
const userId = req.params.userId;
try {
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user.leaveBalance);
} catch (error) {
console.error('Error fetching leave balance:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

// Get leave applications


app.get('/api/leave-applications/:userId', async (req, res) => {
const userId = req.params.userId;
try {
const leaveApplications = await Leave.find({ userId });
res.json(leaveApplications);
} catch (error) {
console.error('Error fetching leave applications:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

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

src/App.js

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


import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import axios from 'axios';

function Register() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleRegister = () => {


axios.post('http://localhost:5000/api/register', { username, password })
.then(response => console.log(response.data))
.catch(error => console.error('Error registering user:', error));
};

return (
<div>
<h2>Register</h2>
<label>Username: <input type="text" value={username} onChange={(e) =>
setUsername(e.target.value)} /></label>
<label>Password: <input type="password" value={password} onChange={(e) =>
setPassword(e.target.value)} /></label>
<button onClick={handleRegister}>Register</button>
</div>
);
}

function Login({ setUserId }) {


const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleLogin = () => {


axios.post('http://localhost:5000/api/login', { username, password })
.then(response => {
console.log(response.data);
setUserId(response.data.userId);
})
.catch(error => console.error('Error logging in:', error));
};
return (
<div>
<h2>Login</h2>
<label>Username: <input type="text" value={username} onChange={(e) =>
setUsername(e.target.value)} /></label>
<label>Password: <input type="password" value={password} onChange={(e) =>
setPassword(e.target.value)} /></label>
<button onClick={handleLogin}>Login</button>
</div>
);
}

function ApplyLeave({ userId }) {


const [leaveType, setLeaveType] = useState('casualLeave');
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');

const handleApplyLeave = () => {


axios.post('http://localhost:5000/api/apply-leave', { userId, leaveType, startDate, endDate })
.then(response => console.log(response.data))
.catch(error => console.error('Error applying leave:', error));
};

return (
<div>
<h2>Apply for Leave</h2>
<label>Leave Type:
<select value={leaveType} onChange={(e) => setLeaveType(e.target.value)}>
<option value="casualLeave">Casual Leave</option>
<option value="medicalLeave">Medical Leave</option>
</select>
</label>
<label>Start Date: <input type="date" value={startDate} onChange={(e) =>
setStartDate(e.target.value)} /></label>
<label>End Date: <input type="date" value={endDate} onChange={(e) =>
setEndDate(e.target.value)} /></label>
<button onClick={handleApplyLeave}>Apply Leave</button>
</div>
);
}

function LeaveBalance({ userId }) {


const [leaveBalance, setLeaveBalance] = useState({ casualLeave: 0, medicalLeave: 0 });

useEffect(() => {
axios.get(`http://localhost:5000/api/leave-balance/${userId}`)
.then(response => setLeaveBalance(response.data))
.catch(error => console.error('Error fetching leave balance:', error));
}, [userId]);

return (
<div>
<h2>Leave Balance</h2>
<p>Casual Leave: {leaveBalance.casualLeave}</p>
<p>Medical Leave: {leaveBalance.medicalLeave}</p>
</div>
);
}

function LeaveApplications({ userId }) {


const [leaveApplications, setLeaveApplications] = useState([]);

useEffect(() => {
axios.get(`http://localhost:5000/api/leave-applications/${userId}`)
.then(response => setLeaveApplications(response.data))
.catch(error => console.error('Error fetching leave applications:', error));
}, [userId]);

return (
<div>
<h2>Leave Applications</h2>
<ul>
{leaveApplications.map(application => (
<li key={application._id}>
<p>Leave Type: {application.leaveType}</p>
<p>Start Date: {application.startDate}</p>
<p>End Date: {application.endDate}</p>
</li>
))}
</ul>
</div>
);
}

function App() {
const [userId, setUserId] = useState('');

return (
<Router>
<div>
<h1>Leave Management System</h1>
<nav>
<ul>
<li><Link to="/register">Register</Link></li>
<li><Link to="/login">Login</Link></li>
{userId && (
<>
<li><Link to="/apply-leave">Apply Leave</Link></li>
<li><Link to="/leave-balance">Leave Balance</Link></li>
<li><Link to="/leave-applications">Leave Applications</Link></li>
</>
)}
</ul>
</nav>
<hr />
<Route path="/register" component={Register} />
<Route path="/login" render={() => <Login setUserId={setUserId} />} />
<Route path="/apply-leave" render={() => <ApplyLeave userId={userId} />} />
<Route path="/leave-balance" render={() => <LeaveBalance userId={userId} />} />
<Route path="/leave-applications" render={() => <LeaveApplications userId={userId} />} />
</div>
</Router>
);
}

export default App;

OUTPUT:

Login Page:
Admin page, Employee Page:

RESULT:
Thus the 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 are created successfully.
EX:NO:7 Develop a simple dashboard for project management where the statuses of
various tasks are available. New tasks can be added and the status of existing
tasks can be changed among Pending, InProgress or Completed.

AIM : To develop a simple dashboard for project management where the statuses of various tasks
are available. New tasks can be added and the status of existing tasks can be changed among
Pending, InProgress or Completed.

ALGORITHM

Step 1: Set up the backend (Node.js + Express)


Create a new directory for your project and navigate to it in the terminal.

mkdir mern-project-management
cd mern-project-management

Step 2: Initialize the backend

npm init -y
npm install express mongoose cors body-parser

Step 3: Create a file server.js for your backend:

Step 4: Set up the frontend (React)


In the same project directory, create a new directory for the frontend

npx create-react-app client

Step 5: Navigate to the client directory:


cd client

Step 6: Install Axios for making HTTP requests:


npm install axios

Step 7: While running the Application


Make sure that MongoDB server is running. Start the backend and frontend

CODING

server.js

const express = require('express');


const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();


const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(bodyParser.json());

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/projectManagement', { useNewUrlParser: true,
useUnifiedTopology: true });
const connection = mongoose.connection;

connection.once('open', () => {
console.log('MongoDB database connection established successfully');
});

// Define the task schema


const taskSchema = new mongoose.Schema({
title: String,
status: String,
});

const Task = mongoose.model('Task', taskSchema);

// API endpoints
app.get('/tasks', (req, res) => {
Task.find((err, tasks) => {
if (err) {
console.log(err);
} else {
res.json(tasks);
}
});
});

app.post('/add', (req, res) => {


const task = new Task(req.body);
task.save()
.then(() => {
res.status(200).json({ 'task': 'task added successfully' });
})
.catch(() => {
res.status(400).send('adding new task failed');
});
});

app.post('/update/:id', (req, res) => {


Task.findById(req.params.id, (err, task) => {
if (!task)
res.status(404).send('data is not found');
else
task.status = req.body.status;

task.save()
.then(() => {
res.json('Task updated');
})
.catch(() => {
res.status(400).send('Update not possible');
});
});
});

app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});

src/App.js

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


import axios from 'axios';

function App() {
const [tasks, setTasks] = useState([]);
const [title, setTitle] = useState('');

useEffect(() => {
axios.get('http://localhost:5000/tasks')
.then(response => {
setTasks(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);

const addTask = () => {


const newTask = { title, status: 'Pending' };
axios.post('http://localhost:5000/add', newTask)
.then(res => console.log(res.data));

setTitle('');
window.location.reload();
};

const updateStatus = (id, status) => {


axios.post(`http://localhost:5000/update/${id}`, { status })
.then(res => console.log(res.data));

window.location.reload();
};

return (
<div>
<h2>Project Management Dashboard</h2>
<div>
<input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
<button onClick={addTask}>Add Task</button>
</div>
<ul>
{tasks.map(task => (
<li key={task._id}>
{task.title} - {task.status}
<button onClick={() => updateStatus(task._id, 'InProgress')}>In Progress</button>
<button onClick={() => updateStatus(task._id, 'Completed')}>Completed</button>
</li>
))}
</ul>
</div>
);
}

export default App;


Output:

Result:
Thus the simple dashboard for project management where the statuses of various tasks are
availabl,in which new tasks can be added and the status of existing tasks can be changed among
Pending, InProgress are Completed successfully.
EX:NO:8 Develop an online survey application where a collection of questions is available
and users are asked to answer any random 5 questions.

AIM : To develop an online survey application where a collection of questions is available and
users are asked to answer any random 5 questions.

ALGORITHM

Step 1: Create the project file using command.


npx create-react-app quiz

Step 2: Navigate to the folder using the command


cd quiz

Step 3: Install the required module using the command.


npm i bootstrap

Step 4: Create a folder named components in src file and create new files Option.js, Question.js,
QuestionBank.js, and Score.js

Project Structure:
PROGRAM

App.js

import React, { Component } from "react";


import "bootstrap/dist/css/bootstrap.min.css";
import Question from "./Components/Question";
import qBank from "./Components/QuestionBank";
import Score from "./Components/Score";
import "./App.css";

class App extends Component {


constructor(props) {
super(props);
this.state = {
questionBank: qBank,
currentQuestion: 0,
selectedOption: "",
score: 0,
quizEnd: false,
};
}

handleOptionChange = (e) => {


this.setState({ selectedOption: e.target.value });
};

handleFormSubmit = (e) => {


e.preventDefault();
this.checkAnswer();
this.handleNextQuestion();
};

checkAnswer = () => {
const { questionBank, currentQuestion, selectedOption, score } = this.state;
if (selectedOption === questionBank[currentQuestion].answer) {
this.setState((prevState) => ({ score: prevState.score + 1 }));
}
};

handleNextQuestion = () => {
const { questionBank, currentQuestion } = this.state;
if (currentQuestion + 1 < questionBank.length) {
this.setState((prevState) => ({
currentQuestion: prevState.currentQuestion + 1,
selectedOption: "",
}));
} else {
this.setState({
quizEnd: true,
});
}
};

render() {
const { questionBank, currentQuestion, selectedOption, score, quizEnd } =
this.state;
return (
<div className="App d-flex flex-column align-items-center justify-content-center">
<h1 className="app-title">QUIZ APP</h1>
{!quizEnd ? (
<Question
question={questionBank[currentQuestion]}
selectedOption={selectedOption}
onOptionChange={this.handleOptionChange}
onSubmit={this.handleFormSubmit}
/>
):(
<Score
score={score}
onNextQuestion={this.handleNextQuestion}
className="score"
/>
)}
</div>
);
}
}

export default App;

Question.js

import React, {Component} from "react";


import Options from "./Option";

class Question extends Component{


render() {
const {question, selectedOption, onOptionChange, onSubmit} = this.props;

return(
<div className="">
<h3>Question {question.id}</h3>
<h5 className="mt-2">{question.question}</h5>
<form onSubmit={onSubmit} className="mt-2 mb-2">
<Options
options={question.options}
selectedOption={selectedOption}
onOptionChange={onOptionChange}
/>
<button type="submit" className="btn btn-primary mt-2">
SUBMIT
</button>
</form>

</div>
)
}
}

export default Question;

Option.js

import React, { Component } from 'react';

class Options extends Component {


render() {
const { options, selectedOption, onOptionChange } = this.props;

return (
<div className='options'>
{options.map((option, index) => (
<div key={index} className="form-check">
<input
type="radio"
name="option"
value={option}
checked={selectedOption === option}
onChange={onOptionChange}
className="form-check-input"
/>
<label className="form-check-label">{option}</label>
</div>
))}
</div>
);
}
}

export default Options;

Score.js

import React, { Component } from 'react';


import '../App.css'

class Score extends Component {


render() {
const { score, onNextQuestion } = this.props;

return (
<div>
<h2>Results</h2>
<h4>Your score: {score}</h4>
</div>
);
}
}

export default Score;

QuestionBank.js

const qBank = [
{
id: 1,
question: "What is the capital of Haryana?",
options: ["Yamunanagar", "Panipat", "Gurgaon", "Chandigarh"],
answer: "Chandigarh",
},
{
id: 2,
question: "What is the capital of Punjab?",
options: ["Patiala", "Ludhiana", "Amritsar", "Chandigarh"],
answer: "Chandigarh",
},
{
id: 3,
question: "What is the capital of India?",
options: ["Delhi", "Mumbai", "Kolkata", "Chennai"],
answer: "Delhi"
},
{
id: 4,
question: "What is the capital of Uttarakhad?",
options: ["Roorkee", "Haridwar", "Dehradun", "Nanital"],
answer: "Dehradun"
},
{
id: 5,
question: "What is capital of Uttar Pradesh?",
options: ["GB Nagar", "Lucknow", "Prayagraj", "Agra"],
answer: "Lucknow"
},
]

export default qBank;


OUTPUT:
Result:
Thus the online survey application where a collection of questions is available and users
are asked to answer any random 5 questions are completed successfully.

You might also like