FSWD LAB
FSWD LAB
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:
Header.js: This component will contain the header section of your portfolio website.
// Header.js
import React from
'react';
// 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>
);
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 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
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.
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
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
App.js
RestaurantList.js
Cart.js
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
- 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
- Item 1
- Price: $10.99
- Item 2
- Price: $8.99
- Item 3
- Price: $12.99
// 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
Frontend (React):
CODING
server.js
app.use(cors());
app.use(express.json());
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
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: '' });
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>
);
}
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.
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
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
CODING
server.js
app.use(cors());
app.use(express.json());
// 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' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
src/App.js
function Register() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
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>
);
}
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>
);
}
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>
);
}
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>
);
}
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
mkdir mern-project-management
cd mern-project-management
npm init -y
npm install express mongoose cors body-parser
CODING
server.js
// 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');
});
// API endpoints
app.get('/tasks', (req, res) => {
Task.find((err, tasks) => {
if (err) {
console.log(err);
} else {
res.json(tasks);
}
});
});
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
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);
});
}, []);
setTitle('');
window.location.reload();
};
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>
);
}
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 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
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>
);
}
}
Question.js
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>
)
}
}
Option.js
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>
);
}
}
Score.js
return (
<div>
<h2>Results</h2>
<h4>Your score: {score}</h4>
</div>
);
}
}
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"
},
]