Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>Javascript HelperNew to Visual Studio Code? Get it now.
Javascript Helper

Javascript Helper

Rockstar

|
1 install
| (0) | Free
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Assignment 1

1. Install and configure Node.js on your computers

Ans:-

Steps to install and configure Node.js:

i) Download Node.js:

a. Go to the official Node.js website.
b. Select appropriate version according to requirement. LTS is more stable.
c. Download the installer for your OS (Windows, macOS, Linux).

ii) Install Node.js:

Execute the downloaded installer.

iii) Verify Installation:

a. After installation, verify that Node.js is installed by opening a terminal/command prompt and running the command:
This will print to the console the installed version of Node.js.

iv) Install and configure Node.js:

a. Set default location of packages:
b. Default global installs go to system directories possibly under administrator privilege.

v) Testing the Setup:

a. Open the terminal/Command prompt and type node and hit enter.
b. This should open up the node environment in it.
c. Write some sample codes to test the working of Node.js.

2. Familiarisation with REPL

a. Execute the following REPL commands

.help .save filename.js .load filename.js console.log("Rushi Madane");

c. Print all odd numbers between 13 and 47

for (let i = 13; i <= 47; i++) {
  if (i % 2 !== 0) {
    console.log(i);
  }
}

3. Solve the Expression (x + y)² Using Functions

function squareSum(x, y) {
  return (x + y) * (x + y);
}

console.log(squareSum(3, 4));

4. Create an HTTP Server to Display Name, Age, and Address

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(`
    <h1>Basic Information</h1>
    <p>Name: Rushi Madane</p>
    <p>Age: 22</p>
    <p>Address: Nerul East</p>
  `);
});

server.listen(3001, () => {
  console.log("Server running at http://localhost:3001");
});

5. Create a Module to Display Current Date and Time

dateTimeModule.js

exports.getDateTime = function () {
  return "Current Date & Time: " + new Date();
};

server.js

const http = require("http");
const dateTime = require("./dateTimeModule");

http
  .createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Hello User!\n" + dateTime.getDateTime());
  })
  .listen(3001);

6. Write a Node.js code to accept a query string from the user on the server through the URL, and write it back to the client.

const http = require("http");
const url = require("url");

const server = http
  .createServer((req, res) => {
    const queryObject = url.parse(req.url, true).query;

    if (queryObject.name && queryObject.age) {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write(
        `<html>
                <body>
                    <h1>Hello ${queryObject.name}, you are ${queryObject.age} years old!</h1>
                </body>
            </html>`
      );
    } else {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write(
        `<html>
                <body>
                    <form method="get" action="/">
                        Enter name: <input type="text" name="name" />
                        Enter age: <input type="number" name="age" />
                        <button>Submit</button>
                    </form>
                </body>
            </html>`
      );
    }

    res.end();
  })
  .listen(3001, () => {
    console.log("Server running at http://localhost:3001/");
  });

7. Write a Node.js code to pass specific input variables through the URL to the server and the server should process them and respond back.

const http = require("http");
const url = require("url");

const server = http
  .createServer((req, res) => {
    const query = url.parse(req.url, true).query;

    const num1 = query.num1;
    const num2 = query.num2;

    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(`
        <html>
            <body>
                <h1>Enter two numbers:</h1>
                <form method="GET" action="/">
                    Number 1: <input type="number" name="num1" required><br><br>
                    Number 2: <input type="number" name="num2" required><br><br>
                    <button type="submit">Submit</button>
                </form>
            </body>
        </html>
    `);

    if (num1 && num2) {
      const sum = Number(num1) + Number(num2);
      res.write(
        `<html>
                <body>
                    <h1>The sum of ${num1} and ${num2} is: ${sum}</h1>
                </body>
            </html>`
      );
    }

    res.end();
  })
  .listen(3001);

8. Write a Node.js code to display your short Bio-Data (along with Photograph) saved in an HTML file in response to the client’s access request to the server.

const http = require("http");
const fs = require("fs");

const server = http
  .createServer((req, res) => {
    const image = fs.readFileSync(__dirname + "/scene.png").toString("base64");

    const htmlContent = `
        <html>
            <body>
                <img src="data:image/png;base64,${image}" alt="img">
                <p><strong>Name:</strong> Rushi Madane</p>
                <p><strong>Age:</strong> 22</p>
                <p><strong>Address:</strong> Nerul East</p>
            </body>
        </html>
    `;

    res.writeHead(200, { "Content-Type": "text/html" });
    res.end(htmlContent);
  })
  .listen(3001);

Assignment 2

1. Write a Node.js code which can create a file “Trial1.txt”. Insert some text in the file and read the same from the file to be displayed.

const fs = require("fs");

const content = "Hello, my name is Rushi.";

fs.writeFile("trail1.txt", content, (err) => {
  if (err) {
    console.error("An error occurred while writing to the file:", err);
    return;
  }
  console.log("File created successfully!");
});
fs.readFile("trail1.txt", "utf8", (err, data) => {
  if (err) {
    console.log(err);
  }
  console.log(data);
});

2. Write a Node.JS code to open an existing file and append the contents of the file. Post updating the file display the contents of the file on the console.

const fs = require("fs");

const filePath = "trail1.txt";

const contentToAppend = "\nThis will appened.";

fs.appendFile(filePath, contentToAppend, (err) => {
  if (err) {
    console.error("An error occurred while appending to the file:", err);
    return;
  }

  console.log("Content appended successfully!");

  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) {
      console.error("An error occurred while reading the file:", err);
      return;
    }

    console.log("Updated file content:\n", data);
  });
});

3. Write a Node.JS code to display the contents (text) of the file on the client side using HTTP server.

const http = require("http");
const fs = require("fs");
const path = require("path");

// Absolute file path
const filePath = "C:\\Users\\rushi\\trail1.txt"; // Make sure the path is correct

const server = http.createServer((req, res) => {
  // Check if the request URL is root
  if (req.url === "/") {
    // Read the content of the file
    fs.readFile(filePath, "utf8", (err, data) => {
      if (err) {
        // Handle file reading error
        res.writeHead(500, { "Content-Type": "text/plain" });
        res.end("An error occurred while reading the file.");
        return;
      }

      // Send the content of the file to the client
      res.writeHead(200, { "Content-Type": "text/plain" });
      res.end(data); // Send the file content to the client
    });
  } else {
    // If the URL is not root, return 404
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("Not Found");
  }
});

const PORT = 8080;
server.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

4. Write a Node.JS code to display on demand the contents of two files (HTML Code) to the client. Use HTTP server.

const http = require("http");
const fs = require("fs");
const path = require("path");

const server = http.createServer((req, res) => {
  if (req.method === "GET") {
    if (req.url === "/site1") {
      const filePath = path.join(__dirname, "site1.html");
      fs.readFile(filePath, "utf8", (err, data) => {
        if (err) {
          res.writeHead(500, { "Content-Type": "text/plain" });
          res.end("Internal Server Error");
        } else {
          res.writeHead(200, { "Content-Type": "text/html" });
          res.end(data);
        }
      });
    } else if (req.url === "/site2") {
      const filePath = path.join(__dirname, "site2.html");
      fs.readFile(filePath, "utf8", (err, data) => {
        if (err) {
          res.writeHead(500, { "Content-Type": "text/plain" });
          res.end("Internal Server Error");
        } else {
          res.writeHead(200, { "Content-Type": "text/html" });
          res.end(data);
        }
      });
    } else {
      res.writeHead(404, { "Content-Type": "text/plain" });
      res.end("404 Not Found");
    }
  } else {
    res.writeHead(405, { "Content-Type": "text/plain" });
    res.end("Method Not Allowed");
  }
});

const PORT = 3001;
server.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

5. Write a Node.JS code to read data from a file and write it into some other file. Display contents of both the files.

const fs = require("fs");
// Read from the first file
fs.readFile("source.txt", "utf8", (err, data) => {
  if (err) throw err;
  // Write to the second file
  fs.writeFile("destination.txt", data, (err) => {
    if (err) throw err;
    console.log("Data written to destination.txt");
    // Display contents of both files
    fs.readFile("destination.txt", "utf8", (err, newData) => {
      if (err) throw err;
      console.log("Source file content:", data);
      console.log("Destination file content:", newData);
    });
  });
});

6. Write a Node.JS code to delete any text file.

const fs = require("fs");
fs.unlink("file1.txt", (err) => {
  if (err) throw err;
  console.log("File deleted");
});

Assignment 3

1. Write a Node.Js code to create a Database Employee and establish a connection.

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
});
con.connect();
const query = "CREATE DATABASE Employee";
con.query(query, (err) => {
  if (err) {
    console.log("Error occured while creating database");
  } else {
    console.log("Successfully created database.");
  }
});
con.end();

2. Write a Node.Js code to Create tables with the following dependencies in the database created in program 10. Insert appropriate records in the tables.

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});

con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
  createDeptTable();
});

function createDeptTable() {
  const createDeptTableQuery = `
    CREATE TABLE IF NOT EXISTS DEPT (
      PTNO INT PRIMARY KEY,
      DNAME VARCHAR(50),
      LOC VARCHAR(50)
    );
  `;
  con.query(createDeptTableQuery, (err) => {
    if (err) {
      console.error("Error creating DEPT table:", err);
      return;
    }
    console.log("DEPT table created");
    insertDeptData();
  });
}

function insertDeptData() {
  const insertDeptDataQuery = `
    INSERT INTO DEPT (PTNO, DNAME, LOC) VALUES
    (10, 'ACCOUNTING', 'NEW YORK'),
    (20, 'RESEARCH', 'DALLAS'),
    (30, 'SALES', 'CHICAGO'),
    (40, 'OPERATIONS', 'BOSTON')
    ON DUPLICATE KEY UPDATE DNAME=VALUES(DNAME), LOC=VALUES(LOC);
  `;
  con.query(insertDeptDataQuery, (err) => {
    if (err) {
      console.error("Error inserting data into DEPT table:", err);
      return;
    }
    console.log("Data inserted into DEPT table");
    createEmpTable();
  });
}

function createEmpTable() {
  const createEmpTableQuery = `
    CREATE TABLE IF NOT EXISTS EMP (
      EMPNO INT PRIMARY KEY,
      ENAME VARCHAR(50),
      JOB VARCHAR(50),
      MGR INT,
      HIREDATE DATE,
      SAL INT,
      COMM INT,
      DEPTNO INT,
      FOREIGN KEY (DEPTNO) REFERENCES DEPT(PTNO)
    );
  `;
  con.query(createEmpTableQuery, (err) => {
    if (err) {
      console.error("Error creating EMP table:", err);
      return;
    }
    console.log("EMP table created");
    insertEmpData();
  });
}

function insertEmpData() {
  const insertEmpDataQuery = `
    INSERT INTO EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO) VALUES
    (7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, NULL, 20),
    (7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600, 300, 30),
    (7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250, 500, 30),
    (7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 2975, NULL, 20),
    (7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250, 1400, 30),
    (7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850, NULL, 30),
    (7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 2450, NULL, 10),
    (7788, 'SCOTT', 'ANALYST', 7566, '1982-12-09', 3000, NULL, 20),
    (7839, 'KING', 'PRESIDENT', NULL, '1981-11-17', 5000, NULL, 10),
    (7844, 'TURNER', 'SALESMAN', 7698, '1981-09-08', 1500, NULL, 30),
    (7876, 'ADAMS', 'CLERK', 7788, '1983-01-12', 1100, NULL, 20),
    (7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950, NULL, 30),
    (7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, NULL, 20),
    (7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, NULL, 10)
    ON DUPLICATE KEY UPDATE ENAME=VALUES(ENAME), JOB=VALUES(JOB), MGR=VALUES(MGR), HIREDATE=VALUES(HIREDATE), SAL=VALUES(SAL), COMM=VALUES(COMM), DEPTNO=VALUES(DEPTNO);
  `;
  con.query(insertEmpDataQuery, (err) => {
    if (err) {
      console.error("Error inserting data into EMP table:", err);
      return;
    }
    console.log("Data inserted into EMP table");
    closeConnection();
  });
}

function closeConnection() {
  con.end((err) => {
    if (err) {
      console.error("Error closing the database connection:", err);
      return;
    }
    console.log("Database connection closed");
  });
}

3. Write a Node.Js code to get the relevant data from the above table/s

- List all employees who have a salary between 1000 and 2000

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});
const query = "SELECT * FROM emp WHERE SAL>1000 AND SAL<2000";
con.query(query, (err, results) => {
  if (err) {
    console.error("Error executing query 1:", err);
    return;
  }
  console.log("Employees with salary between 1000 and 2000:");
  console.table(results);
});

con.end((err) => {
  if (err) {
    console.log(err);
  }
});

- List department numbers and names in department name order

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});
const query =
  "SELECT PTNO AS DepartmentNumber, DNAME AS DepartmentName FROM DEPT ORDER BY DNAME";
con.query(query, (err, results) => {
  if (err) {
    console.error("Error executing query 1:", err);
    return;
  }
  console.table(results);
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

- Display all the different job types.

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});
const query = "SELECT DISTINCT JOB FROM EMP;";
con.query(query, (err, results) => {
  if (err) {
    console.error("Error executing query 1:", err);
    return;
  }
  console.table(results);
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

- List the details of the employees in departments 10 and 20 in alphabetical order of names.

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});
const query = "SELECT * FROM EMP WHERE DEPTNO IN (10, 20) ORDER BY ENAME";
con.query(query, (err, results) => {
  if (err) {
    console.error("Error executing query 1:", err);
    return;
  }
  console.table(results);
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

- Display all employees names which have TH or LL in them

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});
const query =
  "SELECT ENAME FROM EMP WHERE ENAME LIKE '%TH%' OR ENAME LIKE '%LL%'";
con.query(query, (err, results) => {
  if (err) {
    console.error("Error executing query 1:", err);
    return;
  }
  console.table(results);
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

- Display each employee’s name and hiredate from dept. 20

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});
const query = "SELECT ENAME, HIREDATE FROM EMP WHERE DEPTNO = 20";
con.query(query, (err, results) => {
  if (err) {
    console.error("Error executing query 1:", err);
    return;
  }
  console.table(results);
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

- Change the salary of all employees of department 20 such that the salary is increased by Rs.1500/-

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});
const query = "UPDATE EMP SET SAL = SAL + 1500 WHERE DEPTNO = 20";
con.query(query, (err, results) => {
  if (err) {
    console.error("Error executing query 1:", err);
    return;
  }
  console.table(results);
});
const query2 = "SELECT * FROM EMP";
con.query(query2, (err, result) => {
  if (err) {
    console.log(err);
  } else {
    console.log(result);
  }
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

4. Write a Node.Js code to get the relevant data from the above table/s

- Delete all records whose salary is less than Rs.3500/-

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});

const query = "DELETE FROM EMP WHERE SAL < 3500";
con.query(query, (err, result) => {
  if (err) {
    console.log("Error deleting records:", err);
  } else {
    console.log(
      `Deleted ${result.affectedRows} record(s) where salary is less than Rs. 3500.`
    );
  }
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

-Update the commission of all employees who are in department 30 to Rs.600/-

const mysql = require("mysql");

const con = mysql.createConnection({
  host: "localhost",
  user: "reiine",
  password: "123456",
  database: "Employee",
});
con.connect((err) => {
  if (err) {
    console.error("Error connecting to the Employee database:", err);
    return;
  }
  console.log("Connected to the Employee database");
});

const query = "UPDATE EMP SET COMM = 600 WHERE DEPTNO = 30";
con.query(query, (err, result) => {
  if (err) {
    console.log("Error deleting records:", err);
  } else {
    console.log(
      `Updated commission for ${result.affectedRows} employee(s) in department 30.`
    );
  }
});
con.end((err) => {
  if (err) {
    console.log(err);
  }
});

Assignment 4

Q1. Creating the First React Application and setting up the react environment.

Steps:-

a.Check if node is installed by running the command “node –v” . Also check the installation of npm module by running the command “npm –v”.

b.Now, open cmd in the folder where you want to set up a react project.

c.Run the react initialization command “npx create-react-app app-name” to create a react app in the folder.

d.After the command runs, you’ll find a boiler project of react with all the necessary modules and dependencies installed.

Q2.Write a React code for implementing React Component – Function.

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";

const InfoFunc = () => {
  return (
    <div>
      {" "}
      <h1>This is a function</h1>{" "}
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<InfoFunc />);

Q3. Write a React code for implementing React Component – Class.

//Index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

class Info extends React.Component {
  render() {
    return <h1>This is a class</h1>;
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Info />);

Q4. Write a react application to render a Table.

const InfoFunc = () => {
  return (
    <div>
      <table>
        <tr>
          <td>First Name</td>
          <td>Last Name</td>
          <td>Roll No.</td>
        </tr>
        <tr>
          <td>Salman</td>
          <td>Khan</td>
          <td>11</td>
        </tr>
        <tr>
          <td>Tom</td>
          <td>Holland</td>
          <td>59</td>
        </tr>
        <tr>
          <td>Arijit</td>
          <td>Singh</td>
          <td>143</td>
        </tr>
      </table>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<InfoFunc />);

Q5. Write a react application to configure an event.

const InfoFunc = () => {
  const handleClick = () => {
    const date = new Date();
    alert("Today is " + date);
  };
  return (
    <div>
      <button onClick={handleClick}>Click me!</button>
    </div>
  );
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<InfoFunc />);

Q6. Write a react application to demonstrate an event with an argument.

const InfoFunc = () => {
  const [name, setName] = useState("");

  const handleClick = () => {
    alert("Your name is " + name);
  };
  return (
    <div>
      <label>Enter name:</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button onClick={handleClick}>Click me!</button>
    </div>
  );
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<InfoFunc />);

Q7. Write a react code to implement react ‘props’.

const SendProps = () => {
  const data = "This was declared in SendProps function";
  return <InfoFunc data={data} />;
};

const InfoFunc = ({ data }) => {
  return (
    <div>
      <h1>{data}</h1>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<SendProps />);

Q8. Write a react code to design a product information page for an e-commerce portal using ‘props’.

const ProductPage = () => {
  const product = {
    name: "Smartphone XYZ",
    price: "$699",
    description:
      "The latest Smartphone XYZ with high-performance specs, long battery life, and an advanced camera system.",
    imageUrl:
      "https://pluspng.com/img-png/shirt-png-hd-dress-shirt-png-image-dress-shirt-png-914.png",
  };

  return <ProductInfo product={product} />;
};

const ProductInfo = ({ product }) => {
  return (
    <div style={styles.container}>
      <img src={product.imageUrl} alt={product.name} style={styles.image} />
      <h1 style={styles.name}>{product.name}</h1>
      <p style={styles.price}>{product.price}</p>
      <p style={styles.description}>{product.description}</p>
    </div>
  );
};

const styles = {
  container: {
    fontFamily: "Arial, sans-serif",
    textAlign: "center",
    padding: "20px",
    border: "1px solid #ccc",
    borderRadius: "10px",
    maxWidth: "400px",
    margin: "20px auto",
    boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)",
  },
  image: {
    width: "50%",
    borderRadius: "10px",
    marginBottom: "20px",
  },
  name: {
    fontSize: "24px",
    fontWeight: "bold",
    marginBottom: "10px",
  },
  price: {
    fontSize: "20px",
    color: "green",
    marginBottom: "10px",
  },
  description: {
    fontSize: "16px",
    color: "#555",
  },
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<ProductPage />);

Q9. Design a react application to implement a input form.

const InfoFunc = () => {
  const [name, setName] = useState("");

  const handleClick = () => {
    alert("Your name is " + name);
  };

  return (
    <div>
      <label>Enter name:</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button onClick={handleClick}>Click me!</button>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<InfoFunc />);

Q10. Design a form with multiple input using React.

const InfoFunc = () => {
  const [name, setName] = useState("");
  const [age, setAge] = useState("");

  const handleClick = () => {
    alert("Your name is " + name + " and you are " + age + " years old.");
  };

  return (
    <div>
      <label>Enter name:</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <br />
      <label>Enter your age:</label>
      <input
        type="number"
        value={age}
        onChange={(e) => setAge(e.target.value)}
      />
      <br />
      <button onClick={handleClick}>Click me!</button>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<InfoFunc />);

Q11. Design a form with option buttons using React.

Code:-
const InfoFunc = () =>{
  const [name , setName] = useState('');
  const [age, setAge] = useState('');
  const [hobby, setHobby] = useState('');

  const handleClick = () =>{
    alert("Your name is "+name+" and you are "+age+" years old, and you like "+hobby);
  }

  return(
    <div>
      <label>Enter name:</label>
      <input type='text' value={name} onChange={(e)=>setName(e.target.value)} /><br/>
      <label>Enter your age:</label>
      <input type='number' value={age} onChange={(e)=>setAge(e.target.value)}  /><br/>
      <label>What's your hobby?</label>
      <select id='hobby' onChange={(e)=>setHobby(e.target.value)} >
        <option  value='----' >----</option>
        <option value='singing' >Singing</option>
        <option value='dancing' >Dancing</option>
        <option value='travelling' >Travelling</option>
        <option value='coding' >Coding</option>
      </select> <br/>
      <button onClick={handleClick} >Click me!</button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<InfoFunc />);
  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft