MUHAMMAD MUJTABA
SP22-BCS-171
WEB TECHNOLOGIES
LAB ASSIGNMENT #2
QUESTION 1:
CODE :
import React from 'react';
// User component
function User({ name }) {
return <h1>Hello, {name || "Guest"}</h1>;
}
// App component
function App() {
return (
<div>
<User name="MUHAMMAD MUJTABA" /> {/* Passing name prop */}
<User /> {/* No name prop, so defaults to "Guest" */}
</div>
);
}
export default App;
SCREENSHOT:
QUESTION 2:
CODE :
import React, { useState } from 'react';
const Counter = ({ step = 1 }) => {
// Initialize count state with 0
const [count, setCount] = useState(0);
// Increment count by the value of step
const incrementCount = () => {
setCount(prevCount => prevCount + step);
};
return (
<div>
<h1>Current Count: {count}</h1>
<button onClick={incrementCount}>Increment by {step}</button>
</div>
);
};
const App = () => {
return (
<div>
<h2>Counter with default step</h2>
<Counter />
<h2>Counter with custom step</h2>
<Counter step={5} />
</div>
);
};
SCREENSHOT:
QUESTION 3:
CODE :
import React, { useEffect, useRef, useState } from 'react';
const FocusInputComponent = () => {
const inputRef = useRef(null); // useRef to reference the input element
const [inputValue, setInputValue] = useState(''); // State to track the input value
// useEffect to focus on the input field when the component mounts
useEffect(() => {
// Focus the input field when the component mounts
if (inputRef.current) {
inputRef.current.focus();
}
}, []); // Empty dependency array means this effect runs only once (on mount)
// Handle input change and update the state
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div>
<h1>Focus on the Input Field</h1>
<input
ref={inputRef} // Attach the ref to the input element
type="text"
value={inputValue}
onChange={handleChange}
placeholder="Type something..."
/>
<p>Input Value: {inputValue}</p>
</div>
);
};
export default FocusInputComponent;
SCREENSHOT:
QUESTION 4:
CODE :
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
// Home component
function Home() {
return <h1>Welcome to the Home Page</h1>;
}
// About component
function About() {
return <h1>About Us</h1>;
}
// Contact component
function Contact() {
return <h1>Contact Us</h1>;
}
// App component with routes
function App() {
return (
<Router>
<div>
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/about-us" element={<About />} />
<Route path="/contact-us" element={<Contact />} />
</Routes>
</div>
</Router>
);
}
export default App;