React_Labs_Chapters_05_07
zip22 files23 kBIn React labs: chapters 5–7
lab2-solution/5
index.html1 kBpackage.json1 kBREADME.md12 kBvite.config.js1 kBlab2-template/4
index.html1 kBpackage.json1 kBvite.config.js1 kBReact_Lab_Ch05-07_Student.md
React Lab 02 – Chapters 05–07 (Student Guide)
Goal
Build an interactive product catalog application using Props (Chapter 05), Events (Chapter 06), and useState Hook (Chapter 07). Students will create components that pass data via props, handle user interactions through events, and manage state with useState.
Template Requirement
- Locate the provided
lab2-templateReact + Vite project. - Duplicate the folder and rename it using the pattern
react-lab02-<yourname>. - Install dependencies with
npm installfrom inside the duplicated folder. - Do not rename or delete starter files. All new components should live under
src/components.
Predefined Styling
- Keep the stylesheet
src/styles/lab-theme.cssexactly as provided. - When you need new styles, add class names to your JSX and extend the CSS in a separate file (e.g.,
src/styles/extensions.css) that you import intoApp.jsx. - Use the existing utility classes (cards, buttons, forms) to keep a consistent look.
Part 1 – Props with Destructuring & Function Props (Chapter 05)
- Create a file
src/components/ProductCard.jsx. - Export a function component that accepts props using destructuring:
{ id, name, price, description, image, onAddToCart }. - The component should return a
<div className="product-card">containing:- Product image (use
imageprop or a placeholder if not provided) - Product name (from
nameprop) - Product description (from
descriptionprop) - Product price formatted as currency (from
priceprop) - A button with text "Add to Cart" that calls
onAddToCart(id)when clicked
- Product image (use
- Import and test
ProductCardinsidesrc/App.jsx, passing all required props. For now, create a simplehandleAddToCartfunction that logs the product ID to the console. - Verify that clicking the button triggers the function with the correct product ID.
- Stretch: Add an optional
discountprop (number). If provided, display the original price with a strikethrough and show the discounted price in a different color.
Part 2 – Event Handlers (Chapter 06)
- In
src/App.jsx, importuseStatefrom React. - Create state variables using
useState:cartItems(initial value: empty array[])cartCount(initial value:0)
- Update the
handleAddToCartfunction to:- Accept a product ID as parameter
- Find the product from your products array
- Add it to
cartItemsusing the setter function - Update
cartCountby incrementing it
- Create a new component
src/components/CartSummary.jsxthat accepts props:count,total, andonCheckout(function). - Display the cart count and total price in
CartSummary. Add a "Checkout" button that callsonCheckoutwhen clicked. - In
App.jsx, create ahandleCheckoutfunction that usesevent.preventDefault()(if using a form) and alerts a message showing the total items and total price. Then reset the cart (setcartItemsto[]andcartCountto0). - Stretch: Add keyboard support—when the user presses 'Escape' key, clear the cart. Use
onKeyDownevent on a wrapper element.
Part 3 – useState Hook with Multiple States (Chapter 07)
- Add more state variables to
App.jsx:showCart(boolean, defaultfalse) to toggle cart visibilitysearchQuery(string, default"") for filtering products
- Create a component
src/components/SearchBar.jsxthat accepts props:value,onChange, andplaceholder.- It should render an
<input>withtype="text" - Use the
valueandonChangeprops to make it a controlled input - Add an
onFocusevent handler that logs "Search focused"
- It should render an
- In
App.jsx, filter the products array based onsearchQuery. Display only products whose name or description includes the search query (case-insensitive). - Add a toggle button (or icon) in the header that shows/hides the cart. Use the
showCartstate and update it withonClick. - Conditionally render
CartSummaryonly whenshowCartistrue. - Stretch: Add state for
selectedCategory(string). Create category buttons that filter products by category. Use functional updates (setSelectedCategory(prev => ...)) when toggling categories.
Part 4 – Form State Management (Chapter 07)
-
Create a component
src/components/AddProductForm.jsxthat accepts props:onSubmit(function). -
Inside the form component, use
useStateto manage form state as an object:const [formData, setFormData] = useState({ name: '', price: '', description: '', category: '' }) -
Create a
handleChangefunction that updates the form state using the spread operator:const handleChange = (e) => { const { name, value } = e.target setFormData(prev => ({ ...prev, [name]: value })) } -
The form should include input fields for
name,price,description, and aselectdropdown forcategory. All inputs should be controlled (usevalueandonChange). -
Add a submit button. In the form's
onSubmitevent handler, calle.preventDefault()to prevent default form submission. -
Call the
onSubmitprop function with the form data, then reset the form by settingformDataback to its initial state. -
In
App.jsx, create ahandleAddProductfunction that adds the new product to your products array (update the products state). -
Stretch: Add form validation—show an error message if the name is empty or price is not a valid number. Use additional state for error messages.
Deliverables
- A working React project built on the template with all components compiled successfully.
README.mdat the project root containing:- Setup steps you followed.
- Brief description of each component and what props/events it uses.
- Explanation of all state variables and their purposes.
- Any stretch goals you completed.
- Optional reflection file
REFLECTION.mddescribing one challenge per part and how you solved it.
Submission Checklist
- Template duplicated and dependencies installed.
- All components placed under
src/components. -
ProductCarduses prop destructuring and function props (Ch05). - Event handlers implemented for buttons and forms (Ch06).
- Multiple
useStatehooks used for cart, search, and form state (Ch07). - Form state managed as an object with controlled inputs (Ch07).
- Styling uses the provided
lab-theme.cssplus optional extensions. - Application runs without errors:
npm run dev. - README completed with all required information.
Important Reminders:
- Stay within chapters 05–07 only—no useEffect, useContext, or other advanced hooks yet.
- Use functional updates (
setState(prev => ...)) when new state depends on previous state. - Always prevent default form submission with
e.preventDefault(). - Keep event handlers simple and focused—complex logic can go in separate functions.
Good luck, and remember to test each part thoroughly before moving to the next!