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

Lecture 5-6 - React

The document provides a comprehensive overview of React, including multiple choice questions, state management, hooks, and common coding errors. It covers key concepts such as props, state, controlled vs uncontrolled components, the Virtual DOM, and React hooks. Additionally, it includes code examples demonstrating correct implementations and error corrections for various React components.

Uploaded by

moarcarc
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 views12 pages

Lecture 5-6 - React

The document provides a comprehensive overview of React, including multiple choice questions, state management, hooks, and common coding errors. It covers key concepts such as props, state, controlled vs uncontrolled components, the Virtual DOM, and React hooks. Additionally, it includes code examples demonstrating correct implementations and error corrections for various React components.

Uploaded by

moarcarc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Lecture 5-6 - React

Multiple Choice Questions


1. What is React? a) A programming language b) A JavaScript library for building user
interfaces c) A database management system d) A server-side framework

Answer: b) A JavaScript library for building user interfaces - React is a JavaScript


library developed by Facebook for building user interfaces, particularly single-page
applications.

1. What is JSX in React? a) A JavaScript XML syntax extension b) A new programming


language c) A database query language d) A CSS preprocessor

Answer: a) A JavaScript XML syntax extension - JSX is a syntax extension for


JavaScript that looks similar to HTML and allows you to write HTML-like code in your
JavaScript files.

1. Which hook is used to add state to a functional component in React? a) useEffect()


b) useState() c) useContext() d) useReducer()

Answer: b) useState() - The useState hook allows functional components to have state
variables.

1. What is the purpose of the useEffect hook in React? a) To handle form submissions
b) To perform side effects in functional components c) To create new components
d) To style components

Answer: b) To perform side effects in functional components - useEffect is used for


side effects like data fetching, subscriptions, or manually changing the DOM.

1. In React, props are: a) Mutable and can be changed within a component b)


Immutable and cannot be changed within a component c) Only available in class
components d) Only used for styling components

Answer: b) Immutable and cannot be changed within a component - Props (short for
properties) are read-only and should not be modified within a component.

State Questions
1. State the difference between props and state in React components.
Answer: Props (properties) are passed to a component from its parent and are read-only
within the component. They cannot be modified by the component that receives them.
State, on the other hand, is managed within the component itself and can be changed
using setState (in class components) or the state updater function returned by useState
(in functional components). State allows components to create and manage their own
data, while props allow components to receive data from their parent.

1. State what a controlled component is in React and how it differs from an


uncontrolled component.

Answer: A controlled component is a form element whose value is controlled by React


state. The component's value is set by React state and only changes when the state is
updated through event handlers. This creates a single source of truth for the form data.

An uncontrolled component, on the other hand, maintains its own internal state. The
form data is handled by the DOM itself, and values are typically accessed using refs.
Uncontrolled components rely on the DOM to store the form data rather than keeping it
in React state.

1. State the purpose of React fragments and when you would use them.

Answer: React fragments allow you to group multiple elements together without adding
an extra node to the DOM. They're useful when you need to return multiple elements
from a component but don't want to add an unnecessary wrapper div or other container
element that might affect styling or layout. Fragments help keep the DOM cleaner and
can be written using either the explicit <React.Fragment> syntax or the shorthand <>...
syntax.

1. State what the Virtual DOM is in React and how it improves performance.

Answer: The Virtual DOM is a lightweight copy of the actual DOM that React keeps in
memory. When state changes in a React application, React first updates this virtual
representation and then compares it with the previous version (a process called
"diffing"). After identifying the specific changes, React updates only the changed parts in
the real DOM, rather than re-rendering the entire DOM tree.

This improves performance because manipulating the actual DOM is slow and resource-
intensive, while operations on the Virtual DOM are much faster. By minimizing direct
DOM manipulations and batching updates, React reduces browser reflows and repaints,
resulting in better performance, especially in complex applications with frequent
updates.

1. State what React hooks are and name at least three built-in hooks.
Answer: React hooks are functions that allow functional components to use state and
other React features that were previously only available in class components. They let
you "hook into" React state and lifecycle features from function components.

Three built-in hooks are: 1. useState - Allows functional components to have state
variables 2. useEffect - Performs side effects in functional components (similar to
lifecycle methods) 3. useContext - Subscribes to React context without introducing
nesting

Other built-in hooks include useReducer, useCallback, useMemo, useRef,


useLayoutEffect, useDebugValue, and useImperativeHandle.

Code Output Questions


1. What is the output of the following React code?

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

React.useEffect(() => {
setCount(count + 1);
}, []);

return <div>{count}</div>;
}

Answer: 1 - The component initializes count to 0, then the useEffect runs once after the
initial render (due to the empty dependency array [] ), which sets the count to 1. The
component then re-renders with the new count value.

1. What is the output of the following React code?

function Example() {
const [name, setName] = React.useState("John");
return (
<div>
<p>{name}</p>
<button onClick={() => setName("Jane")}>Change Name</button>
</div>
);
}
// After clicking the button once
Answer: After clicking the button once, the output would be: Jane [Change Name
button] Initially, the name state is "John", but when the button is clicked, the setName
function is called with "Jane", updating the state and causing a re-render with the new
value.

1. What is the output of the following React code?

function Parent() {
return (
<Child name="John" />
);
}

function Child({name}) {
return <p>Hello, {name}!</p>;
}

Answer: Hello, John! - The Parent component renders the Child component and passes
"John" as the name prop. The Child component uses destructuring to extract the name
prop and displays it in the paragraph.

1. What is the output of the following React code?

function List() {
const items = ["Apple", "Banana", "Cherry"];
return (
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
);
}

Answer: The output would be an unordered list with three list items: • Apple • Banana •
Cherry The items array is mapped to create an li element for each item, with the item
text displayed inside.

1. What is the output of the following React code?

function Toggle() {
const [isOn, setIsOn] = React.useState(false);

return (
<div>
<p>{isOn ? "ON" : "OFF"}</p>
<button onClick={() => setIsOn(!isOn)}>Toggle</button>
</div>
);
}
// After clicking the button twice

Answer: OFF - Initially, isOn is false, so "OFF" is displayed. After the first click, isOn
becomes true and "ON" is displayed. After the second click, isOn becomes false again, so
the output returns to "OFF".

Find Errors Questions


1. Find and fix the error in the following React code:

function Greeting(props) {
return <h1>Hello, {props.name}<h1>;
}

Answer: The closing h1 tag is missing a forward slash. Corrected code: jsx function
Greeting(props) { return <h1>Hello, {props.name}</h1>; }

1. Find and fix the error in the following React code:

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

return (
<div>
<p>Count: {count}</p>
<button onClick={setCount(count + 1)}>Increment</button>
</div>
);
}

Answer: The onClick handler is immediately invoking setCount instead of passing a


function. This would cause an infinite loop of renders. Corrected code: ```jsx function
Counter() { const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
} ```

1. Find and fix the error in the following React code:

function UserProfile({user}) {
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}

function App() {
return <UserProfile />;
}

Answer: The UserProfile component expects a user prop, but none is provided when it's
rendered in the App component. Corrected code: ```jsx function UserProfile({user})
{ return (

{user.name}
{user.email}

); }

function App() { const user = { name: "John Doe", email: "[email protected]" }; return ; }
```

1. Find and fix the error in the following React code:

function Form() {
const [input, setInput] = useState("");

const handleSubmit = () => {


console.log("Submitted:", input);
};

return (
<form onSubmit={handleSubmit}>
<input value={input} />
<button type="submit">Submit</button>
</form>
);
}
Answer: There are two issues: 1) The form submission event needs to be prevented from
refreshing the page, and 2) the input field needs an onChange handler to update the
state. Corrected code: ```jsx function Form() { const [input, setInput] = useState("");

const handleSubmit = (event) => {


event.preventDefault();
console.log("Submitted:", input);
};

return (
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);

} ```

1. Find and fix the error in the following React code:

function List() {
const items = ["Apple", "Banana", "Cherry"];

return (
<ul>
{items.map(item => <li>{item}</li>)}
</ul>
);
}

Answer: The list items are missing the key prop, which React requires for efficiently
updating lists. Corrected code: ```jsx function List() { const items = ["Apple", "Banana",
"Cherry"];

return (
<ul>
{items.map((item, index) => <li key={index}>{item}</li>)}
</ul>
);

} ``` Note: Using the array index as a key is acceptable for static lists, but for dynamic
lists where items can be added, removed, or reordered, a unique identifier is preferred.
Write/Complete Code Questions
1. Write a React functional component that displays a button and counts the number
of times it has been clicked.

Answer: ```jsx import React, { useState } from 'react';

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

const handleClick = () => {


setCount(count + 1);
};

return (
<div>
<p>Button has been clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);

export default ClickCounter; ```

1. Complete the following React component to fetch and display user data from an
API:

function UserData() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);

// Your code here to fetch data when component mounts

return (
<div>
{/* Your code here to display user data or loading state */}
</div>
);
}

Answer: ```jsx import React, { useState, useEffect } from 'react';

function UserData() { const [user, setUser] = useState(null); const [loading, setLoading] =


useState(true); const [error, setError] = useState(null);
useEffect(() => {
const fetchUser = async () => {
try {
const response = await fetch('https://api.example.com/user');
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
const userData = await response.json();
setUser(userData);
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};

fetchUser();
}, []);

return (
<div>
{loading && <p>Loading user data...</p>}
{error && <p>Error: {error}</p>}
{user && !loading && !error && (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Username: {user.username}</p>
</div>
)}
</div>
);

export default UserData; ```

1. Write a React component that implements a simple form with name and email
fields, and logs the form data when submitted.

Answer: ```jsx import React, { useState } from 'react';

function SimpleForm() { const [formData, setFormData] = useState({ name: '', email: '' });

const handleChange = (e) => {


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

const handleSubmit = (e) => {


e.preventDefault();
console.log('Form submitted:', formData);
// You could also reset the form here if needed
// setFormData({ name: '', email: '' });
};

return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<button type="submit">Submit</button>
</form>
);

export default SimpleForm; ```

1. Complete the following React component to implement a toggle switch:

function ToggleSwitch({ initialState, onToggle }) {


// Your code here
}

Answer: ```jsx import React, { useState, useEffect } from 'react';


function ToggleSwitch({ initialState = false, onToggle }) { const [isOn, setIsOn] =
useState(initialState);

useEffect(() => {
setIsOn(initialState);
}, [initialState]);

const handleToggle = () => {


const newState = !isOn;
setIsOn(newState);
if (onToggle) {
onToggle(newState);
}
};

return (
<div className="toggle-switch">
<div
className={`switch ${isOn ? 'on' : 'off'}`}
onClick={handleToggle}
>
<div className="slider"></div>
</div>
<span>{isOn ? 'ON' : 'OFF'}</span>
</div>
);

export default ToggleSwitch;

// CSS for this component would look something like: // .toggle-switch { display: flex;
align-items: center; } // .switch { position: relative; width: 60px; height: 30px;
background-color: #ccc; border-radius: 15px; cursor: pointer; } // .switch.on
{ background-color: #4cd964; } // .slider { position: absolute; top: 2px; left: 2px; width:
26px; height: 26px; background-color: white; border-radius: 50%; transition:
0.2s; } // .switch.on .slider { transform: translateX(30px); } ```

1. Write a React component that renders a list of items from an array of objects,
where each object has an id and a name property.

Answer: ```jsx import React from 'react';

function ItemList({ items }) { // Default empty array if items prop is not provided const
itemsToRender = items || [];
return (
<div className="item-list">
<h2>Items</h2>
{itemsToRender.length === 0 ? (
<p>No items to display</p>
):(
<ul>
{itemsToRender.map(item => (
<li key={item.id}>
<span className="item-id">#{item.id}</span>
<span className="item-name">{item.name}</span>
</li>
))}
</ul>
)}
</div>
);

export default ItemList;

// Example usage: // const sampleItems = [ // { id: 1, name: "Item One" }, // { id: 2, name:
"Item Two" }, // { id: 3, name: "Item Three" } // ]; // ```

You might also like