Week 5 Assignment
Overview
In this assignment, we will learn the basics of State and Event Handling in React by creating a "Controlled Component." You will build a form that allows users to create a new shopping list item.
Part 1: Initial Setup
- Link to the Week 5 Page
- Edit the project file
/app/page.jsand add a link to week-5. - Create the Folder and Files
- Create the folder /app/week-5.
- Create a file named
page.jsand a file namedNewItem.jsinside it.
Part 2: The NewItem Component
-
Setup the Component
-
In NewItem.js, create a functional component named NewItem. Since this component will use interactivity (hooks), you must add the "use client" directive at the very top of the file.
-
Initialize State
-
Import useState from React.
-
Create three state variables to manage the form inputs:
- name: Initialize as an empty string "".
- quantity: Initialize as 1.
- category: Initialize as "produce".
-
Create the Form UI
-
The component should return a form with the following fields. Use Tailwind CSS to style the form so it is clean and accessible (e.g., max-width, background color, padding).
-
Name Field:
- An input of type text.
- Set the value prop to your name state variable.
- Use the onChange event to update the name state.
- Set required to true.
- Style tip: Use w-full, p-2, and rounded-md.
-
Quantity and Category Row:
- Group these two fields in a flex container so they sit side-by-side.
- Quantity Field:
- An input of type number.
- Min: 1, Max: 99.
- Set the value to your quantity state.
- Update state on change.
-
Category Field:
- A select element.
- Set the value to your category state.
- Update state on change.
- Options: Create option tags for: Produce, Dairy, Bakery, Meat, Frozen Foods, Canned Goods, Dry Goods, Beverages, Snacks, Household, Other.
-
Submit Button:
- A button of type submit.
- Label it "+".
- Style it to look clickable (e.g., blue background, white text, hover effects).
-
Handle the Form Submission
- Create a function named handleSubmit inside your component.
- Prevent Default: Call event.preventDefault() so the page doesn't reload.
- Create Object: Create an item object with the current name, quantity, and category.
- Log the Item: console.log the item object to the console.
- User Feedback: Call alert() to display the details of the created item (e.g., "Added: Bread, quantity: 2, category: bakery").
- Reset State: Reset name to "", quantity to 1, and category to "produce".
- Connect this function to the onSubmit prop of your form element.
- Create a function named handleSubmit inside your component.
Part 3: The Page Component
- Render the Form
- In /app/week-5/page.js:
- Import the NewItem component.
- Create a functional component named Page.
- Render the NewItem component inside a customized main layout (e.g., centered on the screen with a dark background).
- In /app/week-5/page.js:
Part 4: Assignment Submission
- Submit the links to your github repo and deployed site