0% found this document useful (0 votes)
7 views200 pages

Full Stack Development

The document provides a comprehensive guide on full stack development using Express.js, covering routing, HTTP methods, middleware, templating, and form data handling. It includes example programs demonstrating route definitions, data acceptance, retrieval, deletion, and session management, along with detailed instructions on how to set up and run the applications. The document is structured with clear code examples and explanations for each feature implemented.

Uploaded by

pitwstaff2026
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)
7 views200 pages

Full Stack Development

The document provides a comprehensive guide on full stack development using Express.js, covering routing, HTTP methods, middleware, templating, and form data handling. It includes example programs demonstrating route definitions, data acceptance, retrieval, deletion, and session management, along with detailed instructions on how to set up and run the applications. The document is structured with clear code examples and explanations for each feature implemented.

Uploaded by

pitwstaff2026
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

FULL STACK DEVELOPMENT - 2

Experiments:

[Link] – Routing, HTTP Methods, Middleware.

a. Write a program to define a route, Handling Routes, Route Parameters,


Query Parameters and URL building.
Program:

Here's a full working [Link] application that demonstrates:

- Defining routes

- Handling different HTTP methods (GET, POST)

- Using route parameters (`:id`)

- Handling query parameters (`?search=...`)

- URL building using `[Link]()` and `[Link]`

---

Features Covered

| Feature | Example |

|--------------------|--------------------------------|

| Route Definition | `/`, `/about` |

| Route Parameters | `/user/123` |

| Query Parameters | `/search?term=nodejs` |

| HTTP Methods | GET, POST |

| Middleware | Basic logging middleware |

| URL Building | Redirecting to named routes |


Project Structure:

express-routing-demo/

├── [Link]

└── [Link]

1. `[Link]` (You can generate this with `npm init -y`)

```json

"name": "express-routing-demo",

"version": "1.0.0",

"main": "[Link]",

"scripts": {

"start": "node [Link]"

},

"dependencies": {

"express": "^4.18.2"

}
2. `[Link]` – Full Working Express App

```javascript

const express = require('express');

const app = express();

const PORT = 3000;

// Middleware: Request logger

[Link]((req, res, next) => {

[Link](`[${new Date().toISOString()}] ${[Link]} ${[Link]}`);

next();

});

// Built-in middleware to parse form data

[Link]([Link]({ extended: true }));

// Root route

[Link]('/', (req, res) => {

[Link](`

<h1>Welcome to Express Routing Demo</h1>

<ul>

<li><a href="/about">About</a></li>

<li><a href="/user/5">User 5 Profile</a></li>

<li><a href="/search?term=nodejs">Search [Link]</a></li>

<li>
<form action="/submit" method="POST">

<input type="text" name="username" placeholder="Enter username" />

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

</form>

</li>

</ul>

`);

});

// About page

[Link]('/about', (req, res) => {

[Link]('<h2>About Us</h2><p>This is an Express routing demo.</p>');

});

// Route with parameters

[Link]('/user/:id', (req, res) => {

const userId = [Link];

[Link](`<h2>User ID: ${userId}</h2>`);

});

// Route with query parameters

[Link]('/search', (req, res) => {

const searchTerm = [Link] || 'not provided';

[Link](`<h2>You searched for: ${searchTerm}</h2>`);

});
// POST route example

[Link]('/submit', (req, res) => {

const username = [Link];

// Simulate processing and redirect

[Link](`/greet?name=${encodeURIComponent(username)}`);

});

// Greeting route with query param

[Link]('/greet', (req, res) => {

const name = [Link] || 'Guest';

[Link](`<h1>Hello, ${name}!</h1>`);

});

// Start the server

[Link](PORT, () => {

[Link](`Server running at [Link]

});

```

---
How to Run:

1. Install dependencies:

```bash

npm install express

```

2. Run the app:

```bash

node [Link]

```

3. Open your browser and go to:

- [[Link]

Try These URLs

| URL | Description |

|------------------------------------|----------------------------------------|

| `[Link] | Home page |

| `[Link] | About page |

| `[Link] | User profile with route param |

| `[Link] | Search with query param |

| Submit the form on homepage | Posts to `/submit` and redirects to `/greet` |


1.b. Write a program to accept data, retrieve data and delete a specified resource using http methods.

Program:

-Accepting data- via `POST`

-Retrieving data via- `GET`

-Deleting a specified resource- via `DELETE`

| HTTP Method | Route | Description |

|-------------|---------------|---------------------------|

| GET | `/` | Show all items |

| POST | `/add` | Add a new item |

| DELETE | `/delete/:id` | Delete item by ID |

File: `[Link]`:

```js

const express = require('express');

const app = express();

const PORT = 3000;

[Link]([Link]({ extended: true }));

// In-memory "database"

let items = [];

let id = 1;

// Layout function with embedded CSS


const layout = (content) => `

<html>

<head>

<title>Simple CRUD</title>

<style>

body { font-family: sans-serif; padding: 20px; background: #f4f6f8; }

.container { max-width: 500px; margin: auto; background: white; padding: 20px; border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1); }

h1 { text-align: center; color: #333; }

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

li { padding: 10px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; }

input[type="text"] { width: 100%; padding: 10px; margin-top: 10px; border: 1px solid #ccc; border-
radius: 4px; }

button { background: crimson; color: white; border: none; padding: 5px 10px; border-radius: 4px;
cursor: pointer; }

.btn-submit { background: #007BFF; margin-top: 10px; }

</style>

</head>

<body>

<div class="container">

${content}

</div>

</body>

</html>`;

// Show all items

[Link]('/', (req, res) => {


const list = [Link]

? `<ul>${[Link](i => `<li>${[Link]} <form action="/delete/${[Link]}" method="POST"><button


type="submit">Delete</button></form></li>`).join('')}</ul>`

: '<p>No items yet.</p>';

const html = layout(`

<h1>My Items</h1>

${list}

<form method="POST" action="/add">

<input type="text" name="name" placeholder="Enter item name" required />

<button type="submit" class="btn-submit">Add Item</button>

</form>

`);

[Link](html);

});

// Add item

[Link]('/add', (req, res) => {

[Link]({ id: id++, name: [Link] });

[Link]('/');

});

// Delete item

[Link]('/delete/:id', (req, res) => {

items = [Link](i => [Link] != [Link]);

[Link]('/');
});

// Start server

[Link](PORT, () => {

[Link](`Server running at [Link]

});

How to Run

1. Create a file named `[Link]`

2. Paste the code above

3. Install Express:

```bash

npm init -y

npm install express

``

4. Run the server:

bash

node [Link]

5. Open in browser:

- [[Link]
1.c. Write a program to show the working of middleware.

Program:

const express = require('express');

const app = express();

const PORT = 3000;

// Middleware to parse request body

[Link]([Link]());

[Link]([Link]({ extended: true }));

// Home route with form

[Link]('/', (req, res) => {

[Link](`

<h1>Send Data</h1>

<form method="POST" action="/data">

<input type="text" name="name" placeholder="Enter your name" required />

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

</form>

`);

});

// POST route

[Link]('/data', (req, res) => {

const data = [Link];

[Link]({
message: "Data received successfully!",

payload: data

});

});

// Start server

[Link](PORT, () => {

[Link](`Server running at [Link]

});

Output:
2. ExpressJS – Templating, Form Data

a. Write a program using templating engine.


Here's the full updated and working code for your Express + EJS project, including:

- Proper setup of the `views` directory

- Fix for the `ReferenceError: name is not defined`

- Clean structure and comments

Folder Structure:

Experiment_2/a/

├── views/

│ └── [Link]

├── [Link]

1. `[Link]`:

```js

// Import required modules

const express = require('express');

const path = require('path'); // For handling file paths

const app = express();

const PORT = 3002;

// Set EJS as the templating engine

[Link]('view engine', 'ejs');


// Set the correct path to the "views" folder

[Link]('views', [Link](__dirname, 'views'));

// Middleware to parse form data ([Link])

[Link]([Link]({ extended: true }));

// GET route - show form

[Link]('/', (req, res) => {

[Link]('index', { name: null }); // Pass name as null initially

});

// POST route - handle form submission

[Link]('/submit', (req, res) => {

const name = [Link];

[Link]('index', { name }); // Render again with name

});

// Start server

[Link](PORT, () => {

[Link](`Server running at [Link]

});

``

2. `views/[Link]`
```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Express + EJS Demo</title>

<style>

body {

font-family: Arial, sans-serif;

padding: 20px;

background-color: #f4f4f4;

.container {

max-width: 500px;

margin: auto;

background: white;

padding: 30px;

border-radius: 10px;

box-shadow: 0 0 10px rgba(0,0,0,0.1);

text-align: center;

h1 {

color: #333;
}

input[type="text"] {

width: 100%;

padding: 10px;

margin-top: 10px;

border: 1px solid #ccc;

border-radius: 5px;

font-size: 16px;

button {

margin-top: 10px;

padding: 10px 20px;

background-color: #007BFF;

color: white;

border: none;

border-radius: 5px;

font-size: 16px;

cursor: pointer;

button:hover {

background-color: #0056b3;

p{

font-size: 20px;
color: #333;

</style>

</head>

<body>

<div class="container">

<h1>Welcome!</h1>

<% if (name) { %>

<p>Hello, <strong><%= name %></strong>!</p>

<% } else { %>

<form method="POST" action="/submit">

<input type="text" name="name" placeholder="Enter your name" required />

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

</form>

<% } %>

</div>

</body>

</html>

`
How to Run:

1. Open terminal in your project root:

```

PS C:\Users\admin\Desktop\Java_w\Manual Express JS\Experiment_2\a>

```

2. Make sure you've installed dependencies:

```bash

npm install express ejs

``

3. Run the app:

```bash

node [Link]

``

4. Open browser:

- [[Link]
2. ExpressJS – Templating, Form Data

b. Write a program to work with form data.


Features Covered:

| Feature | Description |

|----------------------|-------------|

| Form Submission | Using POST method |

| Form Data Handling | Using `[Link]()` |

| Dynamic Rendering | Show submitted data using EJS |

Folder Structure

```

form-data-demo/

├── views/

│ └── [Link]

├── [Link]

└── [Link]

1. `[Link]` *(Optional, auto-generated)*

Run this command to create it:

```bash

npm init -y

```
Then install dependencies:

```bash

npm install express ejs

```

2. `views/[Link]`:

Create a folder named `views`, and inside it create a file called `[Link]`:

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Form Data Demo</title>

<style>

body { font-family: Arial; padding: 20px; background: #f4f4f4; }

.container {

max-width: 500px;

margin: auto;

background: white;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0,0,0,0.1);

text-align: center;

}
input[type="text"], input[type="email"] {

width: 100%;

padding: 10px;

margin: 10px 0;

border: 1px solid #ccc;

border-radius: 4px;

button {

padding: 10px 20px;

background-color: #007BFF;

color: white;

border: none;

border-radius: 4px;

cursor: pointer;

.output {

margin-top: 20px;

background: #e9ecef;

padding: 15px;

border-radius: 8px;

</style>

</head>

<body>
<div class="container">

<h1>User Registration</h1>

<!-- Show output if data is submitted -->

<% if (formData) { %>

<div class="output">

<p><strong>Name:</strong> <%= [Link] %></p>

<p><strong>Email:</strong> <%= [Link] %></p>

</div>

<% } %>

<!-- Form to submit data -->

<form method="POST" action="/submit">

<input type="text" name="name" placeholder="Enter your name" required />

<input type="email" name="email" placeholder="Enter your email" required />

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

</form>

</div>

</body>

</html>

```

---
## 3. `[Link]` – Full Working Code

```js

const express = require('express');

const path = require('path');

const app = express();

const PORT = 3000;

// Set EJS as the templating engine

[Link]('view engine', 'ejs');

// Set views directory

[Link]('views', [Link](__dirname, 'views'));

// Middleware to parse form data ([Link])

[Link]([Link]({ extended: true }));

// GET route - display form

[Link]('/', (req, res) => {

[Link]('form', { formData: null }); // No data yet

});

// POST route - handle form submission

[Link]('/submit', (req, res) => {


const { name, email } = [Link];

[Link]('form', { formData: { name, email } });

});

// Start server

[Link](PORT, () => {

[Link](`Server running at [Link]

});

How to Run:

1. Make sure you have the correct folder structure.

2. Install dependencies:

```bash

npm install express ejs

```

3. Run the server

```bash

node [Link]

```

4. Open in browser:

- [[Link]
3. ExpressJS – Cookies, Sessions, Authentication

a. Write a program for session management using cookies and sessions.

Program:
Features Covered:

| Feature | Description |

|---------------------|-------------|

| Session Management | Using `express-session` |

| Cookie Support | Stored in browser |

| Authentication | Simulated login |

| Protected Route | Only for logged-in user

Folder Structure:

session-auth-demo/

├── views/

│ ├── [Link]

│ └── [Link]

├── [Link]

└── [Link]

```
1. Install Dependencies:

Run this command in your project folder:

```bash

npm init -y

npm install express ejs express-session

``

2. `views/[Link]`:

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Login</title>

<style>

body { font-family: Arial; padding: 20px; background: #f4f4f4; }

.container {

max-width: 400px;

margin: auto;

background: white;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0,0,0,0.1);

text-align: center;

}
input[type="text"], input[type="password"] {

width: 100%;

padding: 10px;

margin: 10px 0;

border: 1px solid #ccc;

border-radius: 4px;

button {

padding: 10px 20px;

background-color: #007BFF;

color: white;

border: none;

border-radius: 4px;

cursor: pointer;

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

</style>

</head>

<body>

<div class="container">

<h2>Login</h2>

<form method="POST" action="/login">

<input type="text" name="username" placeholder="Username" required />

<input type="password" name="password" placeholder="Password" required />


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

</form>

</div>

</body>

</html>

``

3. `views/[Link]`

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Dashboard</title>

<style>

body { font-family: Arial; padding: 20px; background: #f4f4f4; }

.container {

max-width: 400px;

margin: auto;

background: white;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0,0,0,0.1);

text-align: center;

}
a{

display: inline-block;

margin-top: 20px;

color: #007BFF;

text-decoration: none;

a:hover { text-decoration: underline; }

</style>

</head>

<body>

<div class="container">

<h2>Welcome, <%= username %></h2>

<p>You are logged in!</p>

<a href="/logout">Logout</a>

</div>

</body>

</html>

```

---

## 4. `[Link]` – Full Working Code

```js
const express = require('express');
const session = require('express-session');
const path = require('path');

const app = express();


const PORT = 3004;

// Set EJS as templating engine


[Link]('view engine', 'ejs');
[Link]('views', [Link](__dirname, 'views'));

// Middleware for parsing form data


[Link]([Link]({ extended: true }));

// Session middleware setup


[Link](session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Use true if HTTPS is enabled
}));

// Dummy user (for demo purposes)


const validUser = {
username: 'admin',
password: 'password'
};

// Routes

// Root route - new!


[Link]('/', (req, res) => {
[Link]('/login');
});

// Show login form


[Link]('/login', (req, res) => {
[Link]('login');
});

// Handle login
[Link]('/login', (req, res) => {
const { username, password } = [Link];

if (username === [Link] && password ===


[Link]) {
[Link] = { username };
return [Link]('/dashboard');
}

[Link]('Invalid credentials!');
});

// Dashboard (Protected Route)


[Link]('/dashboard', (req, res) => {
if (![Link]) {
return [Link]('/login');
}

[Link]('dashboard', { username: [Link] });


});

// Logout
[Link]('/logout', (req, res) => {
[Link]((err) => {
if (err) {
return [Link]('/dashboard');
}
[Link]('/login');
});
});

// Start server
[Link](PORT, () => {
[Link](`Server running at [Link]
});
```

How to Run

1. Create the correct folder structure.

2. Install dependencies:

```bash

npm install express ejs express-session

```

3. Run the server:

```bash

node [Link]

```

4. Open in browser:

- [[Link]
3. ExpressJS – Cookies, Sessions, Authentication

b. Write a program for user authentication.


Here's a simple and complete [Link] program that demonstrates user authentication using:

- Sessions (`express-session`)

- In-memory user database (for demo)

- Login & logout functionality

- Protected routes

This example is great for learning how to handle user authentication in Express without any
external libraries beyond `express` and `express-session`.

Features Covered

| Feature | Description |

|---------------------|-------------|

| User Authentication | Simulated login system |

| Session Management | Using `express-session` |

| Protected Routes | Only accessible if logged in |

| In-Memory User DB | For demonstration only |

Folder Structure

auth-demo/

├── views/

│ ├── [Link]

│ └── [Link]

├── [Link]
└── [Link]

```

1. Install Dependencies

Run these commands in your project folder:

```bash

npm init -y

npm install express ejs express-session

```

2. `views/[Link]`

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Login</title>

<style>

body { font-family: Arial; padding: 20px; background: #f4f4f4; }

.container {

max-width: 400px;

margin: auto;

background: white;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0,0,0,0.1);


text-align: center;

input[type="text"], input[type="password"] {

width: 100%;

padding: 10px;

margin: 10px 0;

border: 1px solid #ccc;

border-radius: 4px;

button {

padding: 10px 20px;

background-color: #007BFF;

color: white;

border: none;

border-radius: 4px;

cursor: pointer;

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

.error {

color: red;

margin-bottom: 10px;

</style>

</head>
<body>

<div class="container">

<h2>Login</h2>

<% if (error) { %>

<p class="error"><%= error %></p>

<% } %>

<form method="POST" action="/login">

<input type="text" name="username" placeholder="Username" required />

<input type="password" name="password" placeholder="Password" required />

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

</form>

</div>

</body>

</html>

```

3. `views/[Link]`

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Dashboard</title>

<style>

body { font-family: Arial; padding: 20px; background: #f4f4f4; }


.container {

max-width: 400px;

margin: auto;

background: white;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0,0,0,0.1);

text-align: center;

a{

display: inline-block;

margin-top: 20px;

color: #007BFF;

text-decoration: none;

a:hover { text-decoration: underline; }

</style>

</head>

<body>

<div class="container">

<h2>Welcome, <%= username %></h2>

<p>You are successfully logged in!</p>

<a href="/logout">Logout</a>

</div>
</body>

</html>

```

4. `[Link]` – Full Working Code

```js

const express = require('express');

const session = require('express-session');

const path = require('path');

const app = express();

const PORT = 3000;

// Set EJS as templating engine

[Link]('view engine', 'ejs');

[Link]('views', [Link](__dirname, 'views'));

// Middleware for parsing form data

[Link]([Link]({ extended: true }));

// Session middleware setup

[Link](session({

secret: 'your-secret-key',

resave: false,

saveUninitialized: true,
cookie: { secure: false } // Use true if HTTPS is enabled

}));

// Dummy users (in-memory database)

const users = [

{ id: 1, username: 'admin', password: 'password' },

{ id: 2, username: 'user', password: '1234' }

];

// Root route - redirect to login

[Link]('/', (req, res) => {

[Link]('/login');

});

// Show login form

[Link]('/login', (req, res) => {

[Link]('login', { error: null });

});

// Handle login

[Link]('/login', (req, res) => {

const { username, password } = [Link];

const user = [Link](u => [Link] === username && [Link] === password);
if (user) {

[Link] = { id: [Link], username: [Link] };

return [Link]('/dashboard');

// If invalid credentials

[Link]('login', { error: 'Invalid username or password' });

});

// Dashboard (Protected Route)

[Link]('/dashboard', (req, res) => {

if (![Link]) {

return [Link]('/login');

[Link]('dashboard', { username: [Link] });

});

// Logout

[Link]('/logout', (req, res) => {

[Link]((err) => {

if (err) {

return [Link]('/dashboard');

}
[Link]('/login');

});

});

// Start server

[Link](PORT, () => {

[Link](`Server running at [Link]

});

``

How to Run

1. Make sure the folder structure is correct.

2. Install dependencies:

```bash

npm install express ejs express-session

``

3. Run the app:

```bash

node [Link]

```

4. Open browser:

- [[Link]
4. ExpressJS – Database, RESTful APIs.

a. Write a program to connect MongoDB database using Mangoose and perform


CRUD operations.
Mango DB Installation Guide Video:

[Link]

Program:

Features:

- Connects to MongoDB using Mongoose

- RESTful API for CRUD on `Product`

- Includes root route `/` (for browser access)

- Uses `.env` for configuration

- JSON-based API

Folder Structure:

express-mongo-crud/

├── models/

│ └── [Link]

├── [Link]

├── [Link]

└── .env

```

1. Install Dependencies
```bash

npm init -y

npm install express mongoose dotenv cors helmet morgan

``

2. `.env` File

Create a `.env` file in your project root:

```env

PORT=3000

MONGO_URI=mongodb://localhost:27017/admin

```

> Make sure MongoDB is running locally or use Atlas URI.

3. `models/[Link]` – Mongoose Model:

```js

// models/[Link]

const mongoose = require('mongoose');

const productSchema = new [Link]({

name: {

type: String,

required: true

},

price: {
type: Number,

required: true

},

description: {

type: String

}, { timestamps: true });

[Link] = [Link]('Product', productSchema);

```

4. `[Link]` – Full Working Code:

```js

// [Link]

require('dotenv').config();

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');

const helmet = require('helmet');

const morgan = require('morgan');

const Product = require('./models/Product');

const app = express();

const PORT = [Link] || 3000;


// Middleware

[Link]([Link]());

[Link](cors());

[Link](helmet());

[Link](morgan('dev'));

// MongoDB Connection

[Link]([Link].MONGO_URI, {

useNewUrlParser: true,

useUnifiedTopology: true

})

.then(() => [Link]('✅Connected to MongoDB'))

.catch(err => [Link]('❌MongoDB connection error:', err));

// Root Route

[Link]('/', (req, res) => {

[Link]({ message: 'Welcome to the Product CRUD API!', documentation: 'Use /api/products'
});

});

// Routes

// Create Product - POST /api/products


[Link]('/api/products', async (req, res) => {

try {

const { name, price, description } = [Link];

const product = new Product({ name, price, description });

await [Link]();

[Link](201).json(product);

} catch (err) {

[Link](500).json({ error: 'Server error' });

});

// Get All Products - GET /api/products

[Link]('/api/products', async (req, res) => {

try {

const products = await [Link]();

[Link](products);

} catch (err) {

[Link](500).json({ error: 'Server error' });

});

// Get Single Product - GET /api/products/:id

[Link]('/api/products/:id', async (req, res) => {

try {
const product = await [Link]([Link]);

if (!product) return [Link](404).json({ error: 'Product not found' });

[Link](product);

} catch (err) {

[Link](500).json({ error: 'Server error' });

});

// Update Product - PUT /api/products/:id

[Link]('/api/products/:id', async (req, res) => {

try {

const { name, price, description } = [Link];

const updated = await [Link](

[Link],

{ name, price, description },

{ new: true, runValidators: true }

);

if (!updated) return [Link](404).json({ error: 'Product not found' });

[Link](updated);

} catch (err) {

[Link](500).json({ error: 'Server error' });

});
// Delete Product - DELETE /api/products/:id

[Link]('/api/products/:id', async (req, res) => {

try {

const deleted = await [Link]([Link]);

if (!deleted) return [Link](404).json({ error: 'Product not found' });

[Link]({ message: 'Product deleted successfully' });

} catch (err) {

[Link](500).json({ error: 'Server error' });

});

// Start Server

[Link](PORT, () => {

[Link](`🚀 Server running at [Link]

});

```
Output:
4. ExpressJS – Database, RESTful APIs

b. Write a program to develop a single page application using RESTful APIs.


Program:

Folder Structure:

```

todo-spa/

├── public/

│ └── [Link]

├── models/

│ └── [Link]

├── [Link]

├── [Link]

└── .env

```

1. `.env` – Environment Config:

```env

PORT=3000

MONGO_URI=mongodb://localhost:27017/admin

```

2. `models/[Link]` – Mongoose Model:

```js
// models/[Link]

const mongoose = require('mongoose');

const todoSchema = new [Link]({

task: {

type: String,

required: true

},

completed: {

type: Boolean,

default: false

}, { timestamps: true });

[Link] = [Link]('Todo', todoSchema);

```

3. `public/[Link]` – SPA Frontend:

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>SPA Todo App</title>

<style>
body { font-family: Arial; padding: 20px; background: #f4f4f4; }

.container { max-width: 500px; margin: auto; background: white; padding: 20px; border-
radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }

input[type="text"] { width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid
#ccc; border-radius: 4px; }

button { padding: 10px 15px; background-color: #007BFF; color: white; border: none; border-
radius: 4px; cursor: pointer; }

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

li { padding: 10px; border-bottom: 1px solid #eee; display: flex; justify-content: space-
between; align-items: center; }

.completed { text-decoration: line-through; color: gray; }

</style>

</head>

<body>

<div class="container">

<h2>🚀 Todo List (SPA)</h2>

<input type="text" id="taskInput" placeholder="Enter a new task..." />

<button onclick="addTask()">Add Task</button>

<ul id="taskList"></ul>

</div>

<script>

const API_URL = '/api/todos'; // ✅Correct endpoint

async function fetchTasks() {

try {
const res = await fetch(API_URL);

const todos = await [Link]();

const taskList = [Link]('taskList');

[Link] = '';

[Link](todo => {

const li = [Link]('li');

[Link] = `

<span class="${[Link] ? 'completed' : ''}">${[Link]}</span>

<div>

<button onclick="toggleComplete('${todo._id}', ${![Link]})">✓</button>

<button onclick="deleteTask('${todo._id}')">🚀</button>

</div>

`;

[Link](li);

});

} catch (err) {

[Link]('Error fetching tasks:', err);

async function addTask() {

const taskInput = [Link]('taskInput');

const task = [Link]();

if (!task) return;
try {

const res = await fetch(API_URL, {

method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: [Link]({ task })

});

if (![Link]) throw new Error('Failed to add task');

const data = await [Link]();

[Link] = '';

fetchTasks();

} catch (err) {

[Link]('Error adding task:', err);

alert('Error adding task. See console.');

async function toggleComplete(id, completed) {

try {

const res = await fetch(`${API_URL}/${id}`, {

method: 'PUT',

headers: { 'Content-Type': 'application/json' },


body: [Link]({ completed })

});

if (![Link]) throw new Error('Failed to update task');

fetchTasks();

} catch (err) {

[Link]('Error updating task:', err);

async function deleteTask(id) {

try {

const res = await fetch(`${API_URL}/${id}`, {

method: 'DELETE'

});

if (![Link]) throw new Error('Failed to delete task');

fetchTasks();

} catch (err) {

[Link]('Error deleting task:', err);

}
[Link] = () => {

fetchTasks();

};

</script>

</body>

</html>

```

4. `[Link]` – Full Backend Code:

```js

// [Link]

require('dotenv').config();

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');

const morgan = require('morgan');

const Todo = require('./models/Todo');

const app = express();

const PORT = [Link] || 3000;

// Middleware

[Link]([Link]());
[Link](cors());

[Link](morgan('dev'));

[Link]([Link]('public')); // Serve static files ([Link])

// MongoDB Connection

[Link]([Link].MONGO_URI, {

useNewUrlParser: true,

useUnifiedTopology: true

})

.then(() => [Link]('✅Connected to MongoDB'))

.catch(err => [Link]('❌MongoDB connection error:', err));

// Routes

// Get All Todos

[Link]('/api/todos', async (req, res) => {

try {

const todos = await [Link]();

[Link](todos);

} catch (err) {

[Link](500).json({ error: 'Server error' });

});
// Create Todo

[Link]('/api/todos', async (req, res) => {

try {

const { task } = [Link];

const newTodo = new Todo({ task });

await [Link]();

[Link](201).json(newTodo);

} catch (err) {

[Link](500).json({ error: 'Server error' });

});

// Update Todo by ID

[Link]('/api/todos/:id', async (req, res) => {

try {

const updated = await [Link](

[Link],

[Link],

{ new: true, runValidators: true }

);

if (!updated) return [Link](404).json({ error: 'Task not found' });

[Link](updated);

} catch (err) {

[Link](500).json({ error: 'Server error' });


}

});

// Delete Todo by ID

[Link]('/api/todos/:id', async (req, res) => {

try {

const deleted = await [Link]([Link]);

if (!deleted) return [Link](404).json({ error: 'Task not found' });

[Link]({ message: 'Task deleted successfully' });

} catch (err) {

[Link](500).json({ error: 'Server error' });

});

// Root route (optional)

[Link]('/', (req, res) => {

[Link](__dirname + '/public/[Link]');

});

// Start Server

[Link](PORT, () => {

[Link](`🚀 Server running at [Link]

});

```
How to Run:

1. Install dependencies:

```bash

npm install express mongoose dotenv cors morgan

```

2. Start MongoDB (if not already running):

```bash

mongod

```

3. Start server:

```bash

node [Link]

``

4. Open browser:

```

[Link]

```
Output:
5. ReactJS – Render HTML, JSX, Components – function & Class

a. Write a program to render HTML to a web page.


Program:

Here is the working ReactJS + Webpack setup with all required files for rendering a simple
HTML element using React.

Folder Structure:

```

react-hello/

├── [Link]

├── [Link]

├── [Link]

├── [Link]

1. `[Link]`

```json

"name": "react-hello",

"version": "1.0.0",

"scripts": {

"start": "webpack-dev-server"

},

"dependencies": {
"react": "^18.2.0",

"react-dom": "^18.2.0"

},

"devDependencies": {

"webpack": "^5.74.0",

"webpack-cli": "^5.0.0",

"webpack-dev-server": "^4.11.1",

"babel-loader": "^9.1.2",

"@babel/core": "^7.22.11",

"@babel/preset-env": "^7.22.10",

"@babel/preset-react": "^7.22.5"

``

2. `[Link]`

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>React Render HTML</title>

</head>

<body>
<div id="root"></div>

</body>

</html>

```

3. `[Link]`

```js

import React from 'react';

import ReactDOM from 'react-dom/client';

const App = () => {

return (

<h1>Hello, React! 🚀</h1>

);

};

const root = [Link]([Link]('root'));

[Link](<App />);

4. `[Link]`:

```js

const path = require('path');


[Link] = {

mode: 'development', // Fix the warning

entry: './[Link]',

output: {

filename: '[Link]',

path: [Link](__dirname, '.'),

clean: true,

},

devServer: {

static: './',

hot: true,

open: true

},

module: {

rules: [

test: /\.js$/,

exclude: /node_modules/,

use: {

loader: 'babel-loader',

options: {

presets: ['@babel/preset-env', '@babel/preset-react']

}
}

},

resolve: {

extensions: ['.js', '.jsx']

};

```

How to Run:

1. Initialize and install dependencies:

```bash

npm init -y

npm install react react-dom

npm install --save-dev webpack webpack-cli webpack-dev-server babel-loader @babel/core


@babel/preset-env @babel/preset-react

```

2. Start development server

```bash

npm start

```

Webpack Dev Server will now:

- Compile your React app

- Open browser at: [[Link]


- Show: `Hello, React!

Output in Browser:

You’ll see:

Hello, React!
5. ReactJS – Render HTML, JSX, Components – function & Class

b. Write a program for writing markup with JSX.


Program:

Folder Structure

```

react-app/

├── src/

│ └── [Link]

├── [Link]

├── [Link]

└── .babelrc

```

1. `[Link]`

```json

"name": "react-app-no-html",

"version": "1.0.0",

"scripts": {

"start": "webpack-dev-server"

},

"dependencies": {

"react": "^18.2.0",

"react-dom": "^18.2.0"

},
"devDependencies": {

"webpack": "^5.74.0",

"webpack-cli": "^5.0.0",

"webpack-dev-server": "^4.11.1",

"babel-loader": "^9.1.2",

"@babel/core": "^7.22.11",

"@babel/preset-env": "^7.22.10",

"@babel/preset-react": "^7.22.5",

"html-webpack-plugin": "^5.5.3",

"webpack-dev-server": "^4.11.1"

```

2. `.babelrc`

```json

"presets": ["@babel/preset-env", "@babel/preset-react"]

```

3. `src/[Link]` – Your React Code

```js

import React from 'react';

import ReactDOM from 'react-dom/client';


function App() {

return (

<div style={{ padding: '40px', fontFamily: 'Arial' }}>

<h1>Hello, JSX!</h1>

<p>This is rendered using React without manual [Link]</p>

</div>

);

const root = [Link]([Link]('root'));

[Link](<App />);

4. `[Link]`

```js

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {

mode: 'development',

entry: './src/[Link]',

output: {

filename: '[Link]',

path: [Link](__dirname, 'dist'),

clean: true,
},

devServer: {

static: './dist',

hot: true,

open: true

},

module: {

rules: [

test: /\.js$/,

exclude: /node_modules/,

use: {

loader: 'babel-loader'

},

plugins: [

new HtmlWebpackPlugin({

templateContent: `

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />


<title>React App</title>

</head>

<body>

<div id="root"></div>

</body>

</html>

`,

inject: true

})

],

resolve: {

extensions: ['.js', '.jsx']

};

```

How to Run

1. Initialize and install dependencies

```bash

npm init -y

npm install react react-dom

npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env


@babel/preset-react html-webpack-plugin webpack-dev-server

```

2. Start development server


```bash

npm start

```

Webpack Dev Server will:

- Auto-generate the HTML file

- Inject your React app

- Open browser at: [[Link]

Output:
5. ReactJS – Render HTML, JSX, Components – function & Class

c. Write a program for creating and nesting components (function and class).

Program:

Below is a complete and working ReactJS program that demonstrates:

Creating functional and class-based components

Nesting components inside a parent component

Rendering the final structure in the browser

This example uses modern React syntax (with JSX), and includes all necessary setup
instructions.

Folder Structure
react-component-demo/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc

No [Link] needed — Webpack will auto-generate it using html-webpack-plugin.

1. [Link]
{
"name": "react-component-demo",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. src/[Link] – React Components (Functional & Class)


import React from 'react';
import ReactDOM from 'react-dom/client';

// Functional Component
function Header() {
return (
<header>
<h1>React Component Demo</h1>
</header>
);
}

// Class Component
class Content extends [Link] {
render() {
return (
<main>
<Greeting />
<Features />
</main>
);
}
}

// Nested Functional Component


function Greeting() {
return (
<section>
<h2>Hello, React!</h2>
<p>This is a functional component.</p>
</section>
);
}

// Nested Class Component


class Features extends [Link] {
render() {
return (
<section>
<h2>Features</h2>
<ul>
<li>Functional Components</li>
<li>Class Components</li>
<li>Nested Components</li>
</ul>
</section>
);
}
}

// App Root Component


function App() {
return (
<div>
<Header />
<Content />
</div>
);
}

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);

4. [Link] – Webpack Setup with Auto-Generated


HTML
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development',
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React Component Nesting</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};
How to Run

1. Initialize project

npm init -y

2. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server

3. Start development server


npm start

Webpack Dev Server will open your app at:

[Link]

Output:
6. ReactJS – Props and States, Styles, Respond to Events

a. Write a program to work with props and states.

Program:

Below is a complete and working ReactJS program that demonstrates:

Props – Passing data from parent to child

State – Managing dynamic data in component

Event Handling – Responding to user actions (e.g., button click)

Functional Components with Hooks (useState)

Folder Structure
react-props-state/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc

This project uses html-webpack-plugin so you don't need an [Link].

1. [Link]
{
"name": "react-props-state",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. src/[Link] – Working Code Using Props & State


import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

// Functional Component using Props


function Welcome(props) {
return (
<h2>Hello, {[Link]}!</h2>
);
}

// Functional Component with State and Event Handling


function Counter() {
const [count, setCount] = useState(0);

const increment = () => {


setCount(count + 1);
};

return (
<div>
<p>You clicked <strong>{count}</strong> times</p>
<button onClick={increment}>Click Me</button>
</div>
);
}

// Parent Component passing props


function App() {
return (
<div style={{ padding: '40px', fontFamily: 'Arial' }}>
<Welcome name="Alice" />
<Counter />
</div>
);
}

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);
4. [Link] – Webpack Setup
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development',
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React Props & State Demo</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run

1. Initialize and install dependencies

npm init -y
npm install react react-dom
npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server

2. Start development server


npm start

Webpack Dev Server will open your app at:

[Link]

You’ll see:

Hello, Alice!
You clicked 0 times
[Click Me]

Each time you click the button, the counter increases — demonstrating state management.

Output:
[Link] – Props and States, Styles, Respond to Events .
b. Write a program to add styles (CSS & Sass Styling) and display data.
Program:

Below is the Code For ReactJS program that demonstrates:

Using props and state

Handling events

Applying CSS styling

Fully working in browser

This example includes everything you need to run a complete React app with Webpack,
Babel, and CSS styling — all in one post.

Folder Structure:
react-props-state-css/

├── src/
│ └── [Link]
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc
1. [Link]
{
"name": "react-props-state-css",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3",
"css-loader": "^6.7.3",
"style-loader": "^3.3.2",
"webpack-dev-server": "^4.11.1"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
3. src/[Link] – React Code with Props, State, Events
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
import './[Link]';

// Functional Component using Props


function Welcome(props) {
return (
<h2 className="greeting">Hello, {[Link]}!</h2>
);
}

// Functional Component with State and Event Handling


function Counter() {
const [count, setCount] = useState(0);

const increment = () => {


setCount(count + 1);
};

return (
<div className="counter">
<p>You clicked <strong>{count}</strong> times</p>
<button onClick={increment} className="btn">Click Me</button>
</div>
);
}

// Parent Component passing props


function App() {
return (
<div className="app-container">
<Welcome name="Alice" />
<Counter />
</div>
);
}
// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);

4. src/[Link] – Styling for the App


body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}

.app-container {
max-width: 600px;
margin: 50px auto;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}

.greeting {
color: #007BFF;
margin-bottom: 20px;
}

.counter {
margin-top: 20px;
}

.btn {
padding: 10px 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}

.btn:hover {
background-color: #218838;
}

5. [Link] – Webpack Setup with CSS Support


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development',
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
}, devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React Props & State with CSS</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run

1. Initialize project

npm init -y
2. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin css-loader style-loader webpack-dev-server

3. Start development server

npm start

Webpack will open your app at:

[Link]

Output:
[Link] – Props and States, Styles, Respond to Events.
c. Write a program for responding to events.
Program:

Here is a full working ReactJS program that demonstrates:

Responding to events (onClick, onChange, onSubmit)

Using state with useState

Styling with external CSS

Webpack + Babel setup

No manual [Link] (auto-generated)

This version includes all fixes and optimizations based on the knowledge base, including setting
mode: 'development' in Webpack for better debugging.

Folder Structure
react-event-app/

├── src/
│ ├── [Link]
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc
1. [Link]
{
"name": "react-event-app",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3",
"css-loader": "^6.7.3",
"style-loader": "^3.3.2"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
3. src/[Link] – React Code with Event Handling
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
import './[Link]';

function App() {
const [count, setCount] = useState(0);
const [message, setMessage] = useState('');
const [inputValue, setInputValue] = useState('');

const handleIncrement = () => {


setCount(count + 1);
};

const handleInputChange = (e) => {


setInputValue([Link]);
};

const handleSubmit = (e) => {


[Link]();
if ([Link]()) {
setMessage(`You typed: ${inputValue}`);
setInputValue('');
}
};

return (
<div className="app-container">
<h1>React Event Handling Demo</h1>

{/* Button Click */}


<section>
<h2>Click Counter</h2>
<p>You clicked <strong>{count}</strong> times</p>
<button onClick={handleIncrement} className="btn">Click Me</button>
</section>

<hr />

{/* Input Change */}


<section>
<h2>Type Something</h2>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Type here..."
className="input-field"
/>
<p>{message}</p>
</section>

<hr />

{/* Form Submit */}


<section>
<h2>Submit a Message</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Enter message"
className="input-field"
/>
<button type="submit" className="btn">Submit</button>
</form>
{message && <p>Submitted: {[Link](': ')[1]}</p>}
</section>
</div>
);
}

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);

4. src/[Link] – Styling
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}

.app-container {
max-width: 600px;
margin: 50px auto;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}

.btn {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}

.btn:hover {
background-color: #0056b3;
}

.input-field {
padding: 10px;
width: 250px;
margin-top: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}

h2 {
color: #333;
}
p{
margin-top: 10px;
font-size: 16px;
}

5. [Link] – Webpack Setup with Mode Set


Based on knowledge base — always set mode explicitly for development or production behavior.

const path = require('path');


const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // 🚀 From knowledge base: improves debugging
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true,
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React Event Handling</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run
1. Initialize and install dependencies

npm init -y
npm install react react-dom
npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin css-loader style-loader webpack-dev-server

2. Start development server

npm start
Webpack Dev Server will open your app at:

[Link]

Output:
7. ReactJS – Conditional Rendering, Rendering Lists, React Forms

a. Write a program for conditional rendering.

Program:

complete and working ReactJS program that demonstrates conditional rendering, using:

Functional components

useState hook

Conditional logic (if, ternary operator)

JSX syntax

This example shows how to:

 Toggle visibility of content


 Show/hide a component based on user interaction

Folder Structure
react-conditional-rendering/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc

1. [Link]
{
"name": "react-conditional-rendering",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3",
"css-loader": "^6.7.3",
"style-loader": "^3.3.2"
}
}
2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. src/[Link] – Conditional Rendering Example


import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function App() {
const [isVisible, setIsVisible] = useState(false);

return (
<div style={[Link]}>
<h1>React Conditional Rendering</h1>

{/* Toggle Button */}


<button onClick={() => setIsVisible(!isVisible)} style={[Link]}>
{isVisible ? 'Hide Message' : 'Show Message'}
</button>

{/* Conditional Content */}


{isVisible && (
<div style={[Link]}>
<p>This message is shown conditionally!</p>
</div>
)}

{/* Ternary Example */}


<div style={[Link]}>
<p>{isVisible ? 'You can see the message.' : 'Message is hidden.'}</p>
</div>
</div>
);
}

// Styles as JavaScript object (inline CSS)


const styles = {
container: {
fontFamily: 'Arial',
textAlign: 'center',
padding: '40px'
},
button: {
padding: '10px 20px',
fontSize: '16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
},
messageBox: {
marginTop: '20px',
padding: '20px',
backgroundColor: '#d1ecf1',
color: '#0c5460',
border: '1px solid #bee5eb',
borderRadius: '5px'
},
ternaryBox: {
marginTop: '20px',
fontStyle: 'italic',
color: '#555'
}
};

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);
4. [Link] – Webpack Setup with Babel
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // From knowledge base — enables development optimizations
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true,
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head><title>React Conditional Rendering</title></head>
<body><div id="root"></div></body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

5. How to Run

1. Initialize project

npm init -y

2. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin css-loader style-loader webpack-dev-server

3. Start development server

npm start

Webpack Dev Server will open your app at:

[Link]
Output:
[Link] – Conditional Rendering, Rendering Lists, React Forms
b. Write a program for rendering lists.
Program:

ReactJS program that demonstrates list rendering, using:

Functional components

map() to render dynamic lists

Unique keys for list items

Inline styling

This example shows how to:

 Render a list of items from an array


 Dynamically add new items to the list
 Use keys properly

Folder Structure
react-list-rendering/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc
1. [Link]
{
"name": "react-list-rendering",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
3. src/[Link] – List Rendering Example
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function App() {
const [items, setItems] = useState([
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
]);

const [newItem, setNewItem] = useState('');

const addItem = () => {


if ([Link]()) {
const newItemObj = {
id: [Link](),
name: newItem
};

setItems([...items, newItemObj]);
setNewItem('');
}
};

return (
<div style={[Link]}>
<h1>React List Rendering</h1>

{/* List */}


<ul style={[Link]}>
{[Link](item => (
<li key={[Link]} style={[Link]}>
{[Link]}
</li>
))}
</ul>
{/* Add Item Form */}
<div style={[Link]}>
<input
type="text"
value={newItem}
onChange={(e) => setNewItem([Link])}
placeholder="Add new item"
style={[Link]}
/>
<button onClick={addItem} style={[Link]}>
Add
</button>
</div>
</div>
);
}

// Inline Styles
const styles = {
container: {
fontFamily: 'Arial',
textAlign: 'center',
padding: '40px'
},
list: {
listStyleType: 'none',
padding: 0,
margin: 'auto',
maxWidth: '300px',
textAlign: 'left'
},
listItem: {
padding: '10px',
borderBottom: '1px solid #ddd'
},
form: {
marginTop: '30px'
},
input: {
padding: '10px',
width: '200px',
fontSize: '16px'
},
button: {
marginLeft: '10px',
padding: '10px 15px',
fontSize: '16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}
};

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);
4. [Link] – Webpack Setup
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // From knowledge base — better debugging
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head><title>React List Rendering</title></head>
<body><div id="root"></div></body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run

1. Initialize project

npm init -y
2. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server

3. Start development server


npm start

Webpack Dev Server will open your app at:

[Link]

Output:
[Link] – Conditional Rendering, Rendering Lists, React Forms
c. Write a program for working with different form fields using react
forms.

Program:

working ReactJS program that demonstrates how to work with different form fields using
controlled components:

Features:

 Text Input
 Dropdown Select
 Radio Buttons
 Checkbox
 Multiple Form Fields
 Form Submission
 useState for managing state

Folder Structure
react-form-fields/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc

1. [Link]
{
"name": "react-form-fields",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. src/[Link] – React Form with Multiple Fields


import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function App() {
const [formData, setFormData] = useState({
name: '',
color: 'red',
fruit: 'apple',
newsletter: false
});

const handleChange = (e) => {


const { name, value, type, checked } = [Link];

setFormData({
...formData,
[name]: type === 'checkbox' ? checked : value
});
};

const handleSubmit = (e) => {


[Link]();
alert([Link](formData, null, 2));
};

return (
<div style={[Link]}>
<h1>React Form Example</h1>

<form onSubmit={handleSubmit} style={[Link]}>

{/* Text Input */}


<label style={[Link]}>
Name:
<input
type="text"
name="name"
value={[Link]}
onChange={handleChange}
placeholder="Enter your name"
style={[Link]}
/>
</label>

{/* Dropdown Select */}


<label style={[Link]}>
Favorite Color:
<select
name="color"
value={[Link]}
onChange={handleChange}
style={[Link]}
>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
</label>

{/* Radio Buttons */}


<div style={[Link]}>
<p>Favorite Fruit:</p>
<label style={[Link]}>
<input
type="radio"
name="fruit"
value="apple"
checked={[Link] === 'apple'}
onChange={handleChange}
/>
Apple
</label>
<label style={[Link]}>
<input
type="radio"
name="fruit"
value="banana"
checked={[Link] === 'banana'}
onChange={handleChange}
/>
Banana
</label>
<label style={[Link]}>
<input
type="radio"
name="fruit"
value="orange"
checked={[Link] === 'orange'}
onChange={handleChange}
/>
Orange
</label>
</div>

{/* Checkbox */}


<label style={[Link]}>
<input
type="checkbox"
name="newsletter"
checked={[Link]}
onChange={handleChange}
/>
Subscribe to Newsletter
</label>

{/* Submit Button */}


<button type="submit" style={[Link]}>Submit</button>
</form>

{/* Display Form Data */}


<div style={[Link]}>
<h2>Form Values:</h2>
<pre>{[Link](formData, null, 2)}</pre>
</div>
</div>
);
}

// Inline Styles
const styles = {
container: {
fontFamily: 'Arial',
padding: '40px'
},
form: {
display: 'flex',
flexDirection: 'column',
maxWidth: '400px',
margin: 'auto',
backgroundColor: '#f9f9f9',
padding: '20px',
borderRadius: '10px'
},
label: {
marginBottom: '15px',
display: 'block'
},
input: {
width: '100%',
padding: '8px',
marginTop: '5px',
fontSize: '16px'
},
select: {
width: '100%',
padding: '8px',
marginTop: '5px',
fontSize: '16px'
},
radioGroup: {
marginBottom: '15px'
},
radioLabel: {
display: 'block',
margin: '5px 0'
},
checkboxLabel: {
display: 'block',
marginBottom: '15px'
},
button: {
padding: '10px 20px',
fontSize: '16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
cursor: 'pointer',
borderRadius: '5px'
},
output: {
marginTop: '30px',
textAlign: 'center'
}
};

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);

4. [Link] – Webpack Setup


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // From knowledge base — enables development optimizations
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head><title>React Form Fields</title></head>
<body><div id="root"></div></body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run

1. Initialize project

npm init -y
2. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server

3. Start development server

npm start

Webpack Dev Server will open your app at:

[Link]

Output:
8. ReactJS – React Router, Updating the Screen

a. Write a program for routing to different pages using react router.

Program:

ReactJS program that demonstrates routing to different pages using React


Router v6, including:

Multiple routes

Navigation links

Dynamic route parameters

Conditional rendering based on route

This example uses react-router-dom for client-side routing in a single-page


application (SPA).

Features

Feature Description

React Router v6 Used for navigation between pages


Routing /, /about, /contact, /user/:id

Navigation Using <Link> components

Dynamic Route Shows user ID from URL

Folder Structure

react-router-demo/

├── src/
│ └── [Link]
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc

1. [Link]

{
"name": "react-router-demo",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3"
}
}

2. .babelrc

{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. src/[Link]

import React from 'react';


import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

const root = [Link]([Link]('root'));


[Link](
<BrowserRouter>
<App />
</BrowserRouter>
);

4. src/[Link] – React Router v6 Example

import React from 'react';


import {
Routes,
Route,
Link
} from 'react-router-dom';

// Home Page Component


function Home() {
return (
<div>
<h2>Home</h2>
<p>Welcome to the home page!</p>
</div>
);
}

// About Page Component


function About() {
return (
<div>
<h2>About</h2>
<p>This is the about page.</p>
</div>
);
}
// Contact Page Component
function Contact() {
return (
<div>
<h2>Contact</h2>
<p>You can contact us here.</p>
</div>
);
}

// User Detail Component with Route Param


function User({ params }) {
return (
<div>
<h2>User Profile</h2>
<p>User ID: {[Link]}</p>
</div>
);
}

// Layout Component with Navigation Links


function Layout() {
return (
<div style={[Link]}>
<nav style={[Link]}>
<ul style={[Link]}>
<li><Link to="/" style={[Link]}>Home</Link></li>
<li><Link to="/about" style={[Link]}>About</Link></li>
<li><Link to="/contact" style={[Link]}>Contact</Link></li>
<li><Link to="/user/123" style={[Link]}>View User 123</Link></li>
</ul>
</nav>
<main style={[Link]}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/user/:id" element={<User params={{ id: ':id' }} />} />
</Routes>
</main>
</div>
);
}

// Export App Root


export default function App() {
return <Layout />;
}
const styles = {

container: {
fontFamily: 'Arial, sans-serif',
padding: '20px'
},
nav: {
marginBottom: '20px'
},
navList: {
listStyleType: 'none',
display: 'flex',
gap: '15px',
padding: 0
},
link: {
textDecoration: 'none',
color: '#007BFF',
fontWeight: 'bold'
},
main: {
padding: '20px',
backgroundColor: '#f9f9f9',
borderRadius: '8px'
}
};

5. [Link] – Webpack Setup

const path = require('path');


const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // From knowledge base — better debugging
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head><title>React Router Demo</title></head>
<body><div id="root"></div></body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run:

1. Install dependencies

npm install react react-dom react-router-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core
@babel/preset-env @babel/preset-react html-webpack-plugin webpack-dev-
server
2. Start development server

npm start

[Link] Dev Server will open your app at:

[Link]

You’ll see a navigation bar and content change dynamically when clicking links
like:

 Home
 About
 Contact
 View User 123
Output:
[Link] – React Router, Updating the Screen
b. Write a program for updating the screen.
Program:

ReactJS program that demonstrates how to update the screen dynamically, using:

useState for state management

Event handling (e.g., button click, input change)

Conditional rendering

Dynamic list updates

Inline styling

This example shows how your UI can react to user interactions — such as typing in an input or clicking a
button — to update the screen.

Features

Feature Description

State Management Using useState hook

Screen Updates Triggered by events (onChange, onClick)

Conditional Rendering Based on input value

List Re-rendering Add/remove items from a list

No external libraries Only React + Webpack


Folder Structure
react-screen-update/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc

1. [Link]
{
"name": "react-screen-update",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {

"react": "^18.2.0",

"react-dom": "^18.2.0"

},

"devDependencies": {

"webpack": "^5.74.0",

"webpack-cli": "^5.0.0",

"babel-loader": "^9.1.2",

"@babel/core": "^7.22.11",

"@babel/preset-env": "^7.22.10",

"@babel/preset-react": "^7.22.5",

"html-webpack-plugin": "^5.5.3",
"webpack-dev-server": "^4.11.1"

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. src/[Link] – React Code for Updating the Screen


import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function App() {
const [text, setText] = useState('');
const [displayText, setDisplayText] = useState('');
const [items, setItems] = useState(['Apple', 'Banana', 'Cherry']);
const [newItem, setNewItem] = useState('');

const handleInputChange = (e) => {


setText([Link]);
};

const handleSubmit = (e) => {


[Link]();
if ([Link]()) {
setDisplayText(text);
}
};

const addToList = () => {


if ([Link]()) {
setItems([...items, newItem]);
setNewItem('');
}
};

return (
<div style={[Link]}>
<h1>React: Updating the Screen</h1>

{/* Input Form */}


<form onSubmit={handleSubmit} style={[Link]}>
<input
type="text"
placeholder="Type something"
value={text}
onChange={handleInputChange}
style={[Link]}
/>
<button type="submit" style={[Link]}>Show Text</button>
</form>

{/* Display Updated Text */}


{displayText && (
<div style={[Link]}>
<h2>You typed:</h2>
<p>{displayText}</p>
</div>
)}

<hr style={[Link]} />

{/* Dynamic List Section */}


<div style={[Link]}>
<h2>Fruits List</h2>
<ul style={[Link]}>
{[Link]((item, index) => (
<li key={index} style={[Link]}>{item}</li>
))}
</ul>

<div style={[Link]}>
<input
type="text"
placeholder="Add new item"
value={newItem}
onChange={(e) => setNewItem([Link])}
style={[Link]}
/>
<button onClick={addToList} style={[Link]}>Add Item</button>
</div>
</div>
</div>
);
}

// Inline Styles
const styles = {
container: {
fontFamily: 'Arial',
padding: '40px',
textAlign: 'center'
},
section: {
marginBottom: '40px'
},
input: {
width: '250px',
padding: '10px',
fontSize: '16px',
margin: '10px',
border: '1px solid #ccc',
borderRadius: '4px'
},
button: {
padding: '10px 15px',
fontSize: '16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
},
output: {
marginTop: '20px',
padding: '20px',
backgroundColor: '#f0f8ff',
border: '1px solid #cce0ff',
borderRadius: '5px',
display: 'inline-block',
maxWidth: '500px'
},
list: {
listStyleType: 'none',
padding: 0,
textAlign: 'left',
display: 'inline-block',
width: '100%'
},
listItem: {
padding: '10px',
borderBottom: '1px solid #eee'
},
formGroup: {
marginTop: '20px'
},
hr: {
margin: '40px 0'
}
};

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);

4. [Link] – Webpack Setup with Babel


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // From knowledge base — better debugging
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head><title>React Screen Update</title></head>
<body><div id="root"></div></body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};
How to Run:

1. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server

2. Start development server


npm start

Webpack Dev Server will open your app at:

[Link]

Output:
9. ReactJS – Hooks, Sharing data between Components
[Link] a program to understand the importance of using hooks

Program:

ReactJS program that demonstrates the importance of using hooks, especially useState, to
manage state in functional components.

This example shows how you can:

 Store and update dynamic data


 Re-render UI when state changes
 Share state between elements

Features

Feature Description

useState Hook For managing input field value

Event Handling Updates screen dynamically on input change

Conditional Rendering Based on input

Inline Styling To make it visually clear

Folder Structure
react-hooks-demo/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc
1. [Link]
{
"name": "react-hooks-demo",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
3. src/[Link] – React Code Using useState Hook
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function App() {
const [text, setText] = useState('');
const [showText, setShowText] = useState(false);

const handleInputChange = (e) => {


setText([Link]);
};

const toggleVisibility = () => {


setShowText(!showText);
};

return (
<div style={[Link]}>
<h1>React Hooks: Understanding `useState`</h1>

{/* Input Field */}


<input
type="text"
placeholder="Type something..."
value={text}
onChange={handleInputChange}
style={[Link]}
/>

{/* Toggle Button */}


<button onClick={toggleVisibility} style={[Link]}>
{showText ? 'Hide' : 'Show'} Text
</button>

{/* Conditional Output */}


{showText && (
<div style={[Link]}>
<p>You typed: <strong>{text || 'Nothing yet'}</strong></p>
</div>
)}

<p style={{ marginTop: '20px', fontSize: '14px', color: '#666' }}>


The screen updates automatically because we're using the <code>useState</code> hook.
</p>
</div>
);
}

// Styles as JavaScript object


const styles = {
container: {
fontFamily: 'Arial',
textAlign: 'center',
padding: '40px'
},
input: {
width: '300px',
padding: '10px',
fontSize: '16px',
marginBottom: '20px',
border: '1px solid #ccc',
borderRadius: '4px'
},
button: {
padding: '10px 20px',
fontSize: '16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
},
outputBox: {
marginTop: '20px',
padding: '20px',
backgroundColor: '#f0f8ff',
border: '1px solid #bee5eb',
borderRadius: '5px',
display: 'inline-block'
}
};

// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);

4. [Link] – Webpack Setup with Babel


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // From knowledge base — better debugging
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head><title>React Hooks Demo</title></head>
<body><div id="root"></div></body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run:

1. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server

2. Start development server

npm start
Webpack Dev Server will open your app at:

[Link]

Output:
[Link] – Hooks, Sharing data between Components
b. Write a program for sharing data between components.
Program:

ReactJS program that demonstrates sharing data between components, using:

useState – To manage state in parent component

Props – To pass data from parent to child

Callbacks – To send data back from child to parent

Functional Components – Modern approach using hooks

This example shows how to:

 Share data from parent to child via props


 Update parent state from child

Folder Structure
react-share-data/

├── src/
│ └── [Link]

├── [Link]
├── [Link]
└── .babelrc
1. [Link]
{
"name": "react-share-data",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"babel-loader": "^9.1.2",
"@babel/core": "^7.22.11",
"@babel/preset-env": "^7.22.10",
"@babel/preset-react": "^7.22.5",
"html-webpack-plugin": "^5.5.3"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. src/[Link] – Sharing Data Between Components


import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
// Child Component: Receives data via props and sends data back via callback
function ChildComponent({ message, onSendMessage }) {
const handleSend = () => {
onSendMessage("Hello from Child!");
};

return (
<div style={[Link]}>
<h2>Child Component</h2>
<p><strong>Message from Parent:</strong> {message || 'No message'}</p>
<button onClick={handleSend} style={[Link]}>Send Message to Parent</button>
</div>
);
}

// Parent Component: Holds the state and shares data


function ParentComponent() {
const [childMessage, setChildMessage] = useState('');

const handleMessageFromChild = (msg) => {


setChildMessage(msg);
};

return (
<div style={[Link]}>
<h1>React: Sharing Data Between Components</h1>

{/* Pass data to child */}


<ChildComponent
message="Hi from Parent!"
onSendMessage={handleMessageFromChild}
/>

{/* Display message from child */}


{childMessage && (
<div style={[Link]}>
<h2>Message from Child:</h2>
<p>{childMessage}</p>
</div>
)}
</div>
);
}

// Root Component
export default function App() {
return <ParentComponent />;
}
// Styles as JavaScript object
const styles = {
container: {
fontFamily: 'Arial',
padding: '40px'
},
card: {
border: '1px solid #ccc',
borderRadius: '10px',
padding: '20px',
maxWidth: '400px',
margin: 'auto',
boxShadow: '0 0 10px rgba(0,0,0,0.1)',
textAlign: 'center'
},
outputBox: {
marginTop: '30px',
padding: '20px',
backgroundColor: '#f0f8ff',
border: '1px solid #bee5eb',
borderRadius: '10px',
textAlign: 'center'
},
button: {
padding: '10px 15px',
fontSize: '16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}
};
// Render to DOM
const root = [Link]([Link]('root'));
[Link](<App />);

4. [Link] – Webpack Setup with Babel


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = {
mode: 'development', // From knowledge base — better debugging experience
entry: './src/[Link]',
output: {
filename: '[Link]',
path: [Link](__dirname, 'dist'),
clean: true
},
devServer: {
static: './dist',
hot: true,
open: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
templateContent: `
<!DOCTYPE html>
<html lang="en">
<head><title>React Share Data</title></head>
<body><div id="root"></div></body>
</html>
`,
inject: true
})
],
resolve: {
extensions: ['.js', '.jsx']
}
};

How to Run:
1. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server

2. Start development server

npm start

Webpack Dev Server will open your app at:

[Link]

Output:
10. MongoDB – Installation, Configuration, CRUD operations

a. Install MongoDB and configure ATLAS

Installation Guide:
For Windows:
Refer this Link
[Link]

[Link] – Installation, Configuration, CRUD operations


b. Write MongoDB queries to perform CRUD operations on document using
insert(), find(), update(), remove().

Quires:

CRUD Operations in MongoDB

Let’s assume a students database and a students collection.

A. Create (Insert Documents)

use students // Select or create database


[Link]({
name: "Ravi",
age: 21,
branch: "CSE"
})

Insert multiple:
[Link]([
{ name: "Anita", age: 22, branch: "ECE" },
{ name: "Kiran", age: 20, branch: "MECH" }
])

B. Read (Find Documents)

Find all:

[Link]()

Find with filter:

[Link]({ branch: "CSE" })

Pretty print:

[Link]().pretty()

C. Update Documents

Update one:

[Link](
{ name: "Ravi" },
{ $set: { age: 22 } }
)

Update many:
[Link](
{ branch: "CSE" },
{ $set: { semester: 6 } }
)

D. Delete (Remove) Documents

Delete one:

[Link]({ name: "Anita" })

Delete many:

[Link]({ branch: "MECH" })

Summary Table of CRUD:


Operation Query Example Description
Create insertOne() / insertMany() Add new documents
Read find() / find({}) View documents
Update updateOne() / updateMany() Modify documents
Delete deleteOne() / deleteMany() Remove documents

[Link] – Databases, Collections and Records


a. Write MongoDB queries to Create and drop databases and collections.
Quires:
Reference Video: [Link]

MongoDB queries to create and drop databases and collections, using the MongoDB Shell
(mongosh).

1. Create and Use a Database


In MongoDB, you switch to or create a database using:

use <database_name>

If the database doesn’t exist, it will be created when data is inserted.

Example:

use school

This switches to the school database (or creates it if it doesn't exist).


Now insert a document to actually create the database:

[Link]({ name: "Alice", age: 20 })

2. Drop a Collection
To drop a collection (remove it completely):

db.<collection_name>.drop()

Example:

[Link]()

Output:

 Returns true if successful


 Returns false if collection does not exist

3. Drop a Database
To drop an entire database:

use <database_name> // Switch to the database


[Link]()

Example:

use school
[Link]()

This deletes the entire school database, including all its collections and documents.
How to Run These Queries
1. Open MongoDB Shell:
mongosh

2. Create and use a database:


use school

3. Insert a document to make the database persist:


[Link]({ name: "Alice", age: 20 })

4. Drop the collection:


[Link]()

5. Drop the entire database:


use school
[Link]()

[Link] – Databases, Collections and Records


b. Write MongoDB queries to work with records using find(), limit(), sort(),
createIndex(), aggregate().

Quires:

Here are MongoDB queries to work with records using:

find()
limit()

sort()

createIndex()

aggregate()

These queries are written for the MongoDB Shell (mongosh).

Sample Collection: employees:


Assume we have a collection called employees in a database company.

Insert sample data:

use company

[Link]([
{ name: "Alice", department: "HR", salary: 50000, age: 30 },
{ name: "Bob", department: "IT", salary: 70000, age: 28 },
{ name: "Charlie", department: "IT", salary: 60000, age: 35 },
{ name: "Diana", department: "HR", salary: 48000, age: 25 },
{ name: "Eve", department: "Finance", salary: 80000, age: 40 }
])

1. find() – Query Records

Find all documents:

[Link]().pretty()
Find by condition:

// Find employees in IT department


[Link]({ department: "IT" }).pretty()

// Find employees with salary > 60000


[Link]({ salary: { $gt: 60000 } }).pretty()

2. limit() – Limit Results

Get top 2 highest paid employees:

[Link]().sort({ salary: -1 }).limit(2).pretty()

3. sort() – Sort Records

Sort by salary (ascending):

[Link]().sort({ salary: 1 }).pretty()

Sort by salary (descending):

[Link]().sort({ salary: -1 }).pretty()

Sort by multiple fields:

// Sort by department (asc), then salary (desc)


[Link]().sort({ department: 1, salary: -1 }).pretty()
4. createIndex() – Create Index for Performance

Create index on salary field:

[Link]({ salary: 1 })

Create compound index on department and salary:

[Link]({ department: 1, salary: -1 })

List all indexes:

[Link]()

5. aggregate() – Perform Aggregation

Group by department and calculate average salary:

[Link]([
{
$group: {
_id: "$department",
avgSalary: { $avg: "$salary" },
totalEmployees: { $sum: 1 }
}
}
])

Sort and limit in aggregate:

// Find top 2 highest paid employees


[Link]([
{ $sort: { salary: -1 } },
{ $limit: 2 }
])

Match + Group (Filter + Aggregate)

// Average salary in IT department


[Link]([
{ $match: { department: "IT" } },
{ $group: { _id: null, avgSalary: { $avg: "$salary" } }
])

Summary Table:
Operation Query

find() [Link]({ department: "IT" })

limit() [Link]().sort({ salary: -1 }).limit(2)

sort() [Link]().sort({ salary: -1 })

createIndex() [Link]({ salary: 1 })

aggregate() [Link]([...])
[Link] Programs: (Any 2 must be completed)
a. Design a to-do list application using NodeJS and ExpressJS.
Program:

To-Do List application using:

[Link]

[Link]

MongoDB with Mongoose

RESTful API design

This app allows users to:

 Add tasks
 View all tasks
 Mark task as completed
 Delete tasks

File Structure:

Todo-app/

├── models/
│ └── [Link]

├── routes/

│ └── [Link]

├── views/

│ └── [Link]

├── public/

│ └── [Link]

├── [Link]

├── [Link]

├── .env

└── [Link]

1. [Link] – Project Setup

You can generate this with:

npm init -y

Then install dependencies:

npm install express mongoose ejs dotenv cors helmet morgan


2. .env – Environment Config

PORT=3000
MONGO_URI=mongodb://localhost:27017/todoapp

Make sure MongoDB is running locally or update the URI for Atlas.

3. models/[Link] – Mongoose Model

const mongoose = require('mongoose');

const todoSchema = new [Link]({


task: {
type: String,
required: true
},
completed: {
type: Boolean,
default: false
}
}, { timestamps: true });

[Link] = [Link]('Todo', todoSchema);

4. routes/[Link] – Route Handlers

const express = require('express');


const router = [Link]();
const Todo = require('../models/Todo');
// Get All Todos
[Link]('/', async (req, res) => {
const todos = await [Link]();
[Link]('index', { todos });
});

// Add New Todo


[Link]('/add', async (req, res) => {
const { task } = [Link];
if ([Link]()) {
await [Link]({ task });
}
[Link]('/');
});

// Toggle Completed Status


[Link]('/toggle/:id', async (req, res) => {
const todo = await [Link]([Link]);
[Link] = ![Link];
await [Link]();
[Link]('/');
});

// Delete Todo
[Link]('/delete/:id', async (req, res) => {
await [Link]([Link]);
[Link]('/');
});

[Link] = router;
5. views/[Link] – Dynamic HTML Template

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>To-Do List</title>
<link rel="stylesheet" href="/[Link]" />
</head>
<body>
<div class="container">
<h1>🚀 To-Do List</h1>

<!-- Form to add task -->


<form action="/add" method="POST">
<input type="text" name="task" placeholder="Add a new task..." required />
<button type="submit">Add</button>
</form>

<!-- Task List -->


<ul>
<% [Link](todo => { %>
<li class="<%= [Link] ? 'completed' : '' %>">
<a href="/toggle/<%= todo._id %>">✓</a>
<%= [Link] %>
<a href="/delete/<%= todo._id %>" class="delete">🚀</a>
</li>
<% }) %>
</ul>
</div>
</body>
</html>
6. public/[Link] – Styling

body {
font-family: Arial, sans-serif;
background: #f4f4f4;
padding: 40px;
}

.container {
max-width: 500px;
margin: auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}

h1 {
color: #333;
}

form {
display: flex;
justify-content: center;
gap: 10px;
margin-bottom: 20px;
}

input[type="text"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
padding: 10px 15px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}

ul {
list-style: none;
padding: 0;
text-align: left;
}

li {
padding: 10px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}

.completed {
text-decoration: line-through;
color: gray;
}

.delete {
color: red;
text-decoration: none;
}

7. [Link] – Express App Using Webpack Mode Configuration


(from knowledge base)

require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const app = express();
const PORT = [Link] || 3000;

// Set mode-based optimizations


const webpackModeConfig = (env, argv) => {
if ([Link] === 'development') {
[Link]((req, res, next) => {
[Link](`[DEV] Request: ${[Link]} ${[Link]}`);
next();
});
}
};

webpackModeConfig(null, { mode: [Link].NODE_ENV || 'production' });

// Middleware
[Link]('view engine', 'ejs');
[Link]('views', [Link](__dirname, 'views'));
[Link]([Link]({ extended: true }));
[Link]([Link]('public'));
// Routes
const todoRoutes = require('./routes/todoRoutes');
[Link](todoRoutes);

// MongoDB Connection
[Link]([Link].MONGO_URI)
.then(() => {
[Link]('✅Connected to MongoDB');
// Start server
[Link](PORT, () => {
[Link](`🚀 Server running at [Link]
});
})
.catch(err => {
[Link]('❌MongoDB connection error:', err);
});

8. [Link]:
const path = require('path');

const webpackModeConfig = { entry: './[Link]', output: { filename: '[Link]', path:


[Link](__dirname, 'dist') } };

[Link] = (env, argv) => { if ([Link] === 'development') { [Link] =


'source-map'; [Link]('Running in development mode with source maps'); }

if ([Link] === 'production') { // Add minification or other optimizations [Link]('Running in


production mode'); }

return webpackModeConfig; };
9. [Link]:
{

"name": "todo-app",

"version": "1.0.0",

"description": "A simple To-Do List app using Express and MongoDB",

"main": "[Link]",

"scripts": {

"start": "node [Link]"

},

"dependencies": {

"cors": "^2.8.5",

"dotenv": "^16.3.1",

"ejs": "^3.1.9",

"express": "^4.18.2",

"helmet": "^6.1.0",

"mongoose": "^7.0.3",

"morgan": "^1.10.0"

},

"devDependencies": {},

"engines": {

"node": ">=14"

},

"author": "Your Name",

"license": "MIT"

}
How to Run:

1. Initialize and install dependencies

npm install express mongoose ejs dotenv cors helmet morgan

2. Start Express server

node [Link]

Open in browser:

[Link]

Output:
[Link] Programs: (Any 2 must be completed)
b. Design a Quiz app using ReactJS.
Program:

Quiz App using ReactJS.

This is a front-end only version (no backend), and includes:

Multiple-choice quiz
State management with useState

Conditional rendering

Score tracking

Styled with inline CSS

You can expand this later to include a backend using Express + MongoDB.

Folder Structure
react-quiz-app/

├── public/

│ └── [Link]

├── src/

│ ├── [Link]

│ └── [Link]

├── styles/

│ └── [Link]

├── [Link]

├── [Link]

└── .babelrc
1. [Link]
{
"name": "react-quiz-app",
"version": "1.0.0",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@babel/core": "^7.28.0",
"@babel/preset-env": "^7.28.0",
"@babel/preset-react": "^7.27.1",
"babel-loader": "^9.2.1",
"css-loader": "^7.1.2",
"html-webpack-plugin": "^5.6.3",
"style-loader": "^4.0.0",
"webpack": "^5.100.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.2"
}
}

2. .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
3. src/[Link] – React Quiz App
import React, { useState } from 'react';
import '../styles/[Link]';

function App() {
const [currentQuestion, setCurrentQuestion] = useState(0);
const [score, setScore] = useState(0);
const [showScore, setShowScore] = useState(false);

const questions = [
{
questionText: "What does ReactJS primarily use for state management?",
options: [
{ answerText: "Redux", isCorrect: true },
{ answerText: "jQuery", isCorrect: false },
{ answerText: "Axios", isCorrect: false },
{ answerText: "Express", isCorrect: false }
]
},
{
questionText: "Which company developed ReactJS?",
options: [
{ answerText: "Google", isCorrect: false },
{ answerText: "Facebook", isCorrect: true },
{ answerText: "Netflix", isCorrect: false },
{ answerText: "Twitter", isCorrect: false }
]
},
{
questionText: "What is ReactJS?",
options: [
{ answerText: "A library for building UI", isCorrect: true },
{ answerText: "A framework for server-side rendering", isCorrect: false },
{ answerText: "A database", isCorrect: false },
{ answerText: "A styling tool", isCorrect: false }
]
},
{
questionText: "Which of the following is used to pass data to a component in React?",
options: [
{ answerText: "Events", isCorrect: false },
{ answerText: "Hooks", isCorrect: false },
{ answerText: "Props", isCorrect: true },
{ answerText: "State", isCorrect: false }
]
},
{
questionText: "Which hook is used to manage state in React?",
options: [
{ answerText: "useEffect", isCorrect: false },
{ answerText: "useState", isCorrect: true },
{ answerText: "useRef", isCorrect: false },
{ answerText: "useContext", isCorrect: false }
]
}
];

const handleAnswerClick = (isCorrect) => {


if (isCorrect) {
setScore(score + 1);
}

const nextQuestion = currentQuestion + 1;


if (nextQuestion < [Link]) {
setCurrentQuestion(nextQuestion);
} else {
setShowScore(true);
}
};

const restartQuiz = () => {


setCurrentQuestion(0);
setScore(0);
setShowScore(false);
};

return (
<div className="container">
<h1>React Quiz App</h1>

{showScore ? (
<div className="score-section">
<h2>You scored {score} out of {[Link]}</h2>
<button onClick={restartQuiz} className="restart-button">
Restart Quiz
</button>
</div>
):(
<>
<div className="question-section">
<div className="question-count">
<span>Question {currentQuestion + 1}/{[Link]}</span>
</div>
<div className="question-text">
{questions[currentQuestion].questionText}
</div>
</div>

<div className="answer-section">
{questions[currentQuestion].[Link]((option, index) => (
<button
key={index}
onClick={() => handleAnswerClick([Link])}
className="answer-button"
>
{[Link]}
</button>
))}
</div>
</>
)}
</div>
);
}

export default App;

4. src/[Link] – React Quiz App

import React from 'react';


import ReactDOM from 'react-dom/client';
import App from './[Link]';

const root = [Link]([Link]('root'));


[Link](<App />);
[Link]/[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>React Quiz App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

[Link]/[Link]:
/* Base Styles */
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}

body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}

.container {
text-align: center;
padding: 40px;
max-width: 600px;
background: white;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}
h1 {
font-size: 2.5rem;
margin-bottom: 20px;
color: #333;
}

/* Question Section */
.question-section {
margin-bottom: 30px;
}

.question-count {
font-size: 18px;
margin-bottom: 10px;
color: #555;
}

.question-text {
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
color: #222;
}

/* Answer Buttons */
.answer-section {
display: flex;
flex-direction: column;
gap: 10px;
max-width: 400px;
margin: auto;
}

.answer-button {
padding: 15px;
font-size: 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.answer-button:hover {
background-color: #0056b3;
}

/* Score Section */
.score-section {
font-size: 20px;
}

.score-section h2 {
margin-bottom: 20px;
color: #333;
}

.restart-button {
padding: 10px 20px;
font-size: 16px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}

.restart-button:hover {
background-color: #218838;
}

[Link]:
// [Link]

const path = require('path');


const HtmlWebpackPlugin = require('html-webpack-plugin');

[Link] = (env, argv) => {


return {
mode: [Link] || 'development',
entry: './src/[Link]',
output: {
path: [Link](__dirname, 'dist'),
filename: '[Link]'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'] // Process .css files
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/[Link]'
})
],
resolve: {
extensions: ['.js', '.jsx']
},
devServer: {
static: './dist',
hot: true,
open: true
}
};
};
How to Run:

1. Install dependencies

npm install react react-dom


npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env
@babel/preset-react html-webpack-plugin webpack-dev-server
2. Start development server

npm start

Webpack Dev Server will open your app at:

[Link]

Output:
12. Augmented Programs: (Any 2 must be completed)

c. Complete the MongoDB certification from MongoDB University website.

Instructions:

Detailed and beginner-friendly guide on how to complete the MongoDB


Certification from MongoDB University, especially helpful for students doing
"Augmented Programs – Task 12c":

Task 12c: Complete the MongoDB Certification from


MongoDB University

MongoDB University offers free online courses and certifications that you can
complete at your own pace. Here’s how to do it:
Step-by-Step Guide to Complete MongoDB Certification

🔹 Step 1: Go to MongoDB University

[Link]

🔹 Step 2: Sign Up / Log In

 Click “Sign Up” (use your email or GitHub/Google account)


 OR click “Login” if you already have an account

🔹 Step 3: Choose a Certification Course

You can choose any one course from below:

Course Name Ideal For


M001: MongoDB Basics Beginners
M103: Basic Cluster Administration Admins
M121: Aggregation Framework Developers
M220P: MongoDB for Python Developers Python users
M220JS: MongoDB for JavaScript Developers Web developers

🚀 Recommended for Students: M001 - MongoDB Basics (4–5 hours)

🔹 Step 4: Enroll & Start Learning

 Click on "Enroll" button


 Watch video lectures
 Do the quizzes & lab exercises after each chapter
🔹 Step 5: Complete All Modules

 Finish all chapters and pass all labs/quizzes


 It’s self-paced, but you can finish in 1–2 days

🔹 Step 6: Get Your Certificate

 Once done, your certificate will be automatically generated


 Go to Dashboard → Completed Courses → View Certificate
 Click “Download Certificate” (PDF format)

Step 7: Submit Proof

 Take a screenshot or submit the PDF of your MongoDB certificate


 Submit it to your instructor/portal to complete Task 12c

Summary for Students


Task Description
Platform [Link]
Course to Choose M001: MongoDB Basics
Format Video + Labs + Quizzes
Time Required 4–5 hours
Certificate Issued after successful completion
Cost ✅Free

You might also like