FAQ: React Forms - React Forms Recap

This community-built FAQ covers the “React Forms Recap” exercise from the lesson “React Forms”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Learn ReactJS: Part II

FAQs on the exercise React Forms Recap

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Regarding the optional exercise on the last page, where we had to create a form for a school administrator.
I managed to get it to work, but I feel like it was very long and repetetive. For each of the 6 pieces of data we were asked for (first name, last name etc) I made an with corresponding , then a state and state setter, and event handler function. e.g.

const [firstNameInput, setFirstNameInput] = useState("");

  function changeFirstName(e) {
     setFirstNameInput(e.target.value);
  };
 <label for="firstName">First name:</label>
      <input onChange={changeFirstName} value={firstNameInput} style={formStyle} id="firstName"/> 

I then followed this pattern for the other 5. This feels like a lot of code to me!
I experimented with an array

const fields = ['First name', 'Last name', 'Age', 'Address', 'Homeroom class number', 'Student ID']

then mapped over this to create a label and button for each one, but the trouble with this was (1) I couldn’t differentiate type=“text” and type=“number” and (2) I couldn’t set the value attribute as I needed it to be unique for each one. And even then, they all had the same event handler, so when I typed in one field, all fields updated.

My other thought was to initialise the state as an empty object and add the input to the object as the user typed, which worked to a point, but then I struggled with accessing the values within the object to be able to display. (As my keys were strings with multiple words, I couldn’t use dot notation, but bracket notation didn’t seem to work.)
How did other people tackle this? Thanks in advance!

Hello, i have the same issue as you do!
I va also repeated the function 5 times and it seems the its too much and that it should more automised solution… I dont really get how could you do that with an array thought…
Anyways Im happy to check the other answers if someone could resolved it!!

I searched online and found this page on StackOverflow: https://stackoverflow.com/questions/59813926/how-can-i-store-and-update-multiple-values-in-react-usestate.

We didn’t learn this approach via the Intro to React lesson so I haven’t tried it yet, but it looks like you can use a single State hook for all values and then have an <input> tag for each value you want, specifying what type each input tag is.

1 Like

we actualy did learn about multiple states.

import React, { useState, useEffect } from "react";

function StudentForm() {
  const lunch = ["pizza", "burger", "curry", "salad", "stirfry"];
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    age: "",
    address: "",
    classNumber: "",
    studentId: "",
    favoriteLunch: "",
  });

  function handleChange(e) {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  }
  return (
    <>
      <div>
        <h1>School form admission </h1>
        <form>
          <label htmlFor="firstName">First Name: </label>
          <input
            value={formData.firstName}
            id="firstName"
            type="text"
            onChange={handleChange}
            name="firstName"
          />
          <p>Firstname is: {formData.firstName}</p>
          <label htmlFor="lastName">Last Name: </label>
          <input
            value={formData.lastName}
            id="lastName"
            type="text"
            onChange={handleChange}
            name="lastName"
          />
          <p>Lastname is: {formData.lastName}</p>
          <label htmlFor="age">Age: </label>
          <input
            value={formData.age}
            id="age"
            type="text"
            onChange={handleChange}
            name="age"
          />
          <p>Age is: {formData.age}</p>
          <label htmlFor="address">Address: </label>
          <input
            value={formData.address}
            id="address"
            type="text"
            onChange={handleChange}
            name="address"
          />
          <p>Address is: {formData.address}</p>
          <label htmlFor="classNumber">Class Number: </label>
          <input
            value={formData.classNumber}
            id="classNumber"
            type="text"
            onChange={handleChange}
            name="classNumber"
          />
          <p>Class number is: {formData.classNumber}</p>
          <label htmlFor="studentId">Student ID: </label>
          <input
            value={formData.studentId}
            id="studentId"
            type="text"
            onChange={handleChange}
            name="studentId"
          />
          <p>Student ID is: {formData.studentId}</p>
          <div style={{ display: "flex", alignItems: "center" }}>
            <p>Favourite lunch:</p>

            {lunch.map((option, index) => (
              <label key={index}>
                <input
                  key={index}
                  value={option}
                  id={`lunch-${option}`}
                  type="radio"
                  onChange={handleChange}
                  name="favoriteLunch"
                  checked={formData.favoriteLunch === option}
                />
                {option}
              </label>
            ))}
          </div>
        </form>
      </div>
    </>
  );
}

export default StudentForm;

took me a while to workout how to use only one useState but it was a good challenge!