skip to Main Content

I have set an initial state to store all of the values from my form. However, in order to tell the program that I’m targetting a checkbox I need to specify the type:

e.target.type === 'checkbox'

Even though it works I feel like I shouldn’t need to specify the type in order to pull it’s value. Can anyone tell me if this is the correct way to do it or if I’m missing something, please?

My STATE prints username, lastname and accept fields when interacting with the form, example:

{username: "Mike", lastname: "Brown", accept: true}

and here’s a working DEMO:

2

Answers


  1. Perhaps you can look at Formik and Yup. They can help you build forms with validation and they also integrate with UI libraries like Material UI.

    Login or Signup to reply.
  2. If you don’t want to use a conditional in your handleChange, you can pass the value directly to the function like this:

    const handleChange = (attribute, value) =>
      setInitialState((prev) => ({
        ...prev,
        [attribute]: value
      }));
    

    And in your form use it like this:

    return (
      <form>
        <input
          type="text"
          value={username}
          onChange={(e) => handleChange("name", e.target.value)}
        />
        <input
          type="checkbox"
          checked={accept}
          onChange={(e) => handleChange("accept", e.target.checked)}
        />
      </form>
    );
    

    Hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search