简体   繁体   中英

React hooks, grab value of checkbox onChange and pass to submitForm

I currently have a working hook, that checks the onChange of input fields, then spreads (I think that is the term for ... ) them into a variable and send's them to a Lamda function to send a email with sendgrid. All of that is working.

However if I add a input type of checkbox I am a little lost on the logic side. Because I am checking for the target's name and pairing that with it's value. Well the checkbox has a checked state not a value. I assume I have to do something like e.target.checked in my setFormState however how do I do that as well as the e.target.value and still spread it to ...formState ?

I am a react noob.

Here is my react state and the change event and submit event

const [formState, setFormState] = React.useState({
    name: "",
    package: `${data.datoCmsPricing.title}`,
    email: "",
    subject: "",
    weightLoss:"",
    message: "",
  })

  const onChange = (e) => {
    setFormState({...formState, [e.target.name]: e.target.value });
 }

 const submitForm = async (e) => {
  e.preventDefault();

  console.log("test");

  try{
    const response = await fetch("/.netlify/functions/sendmail", {
      method: "POST",
      body: JSON.stringify(formState),
    })

    if (!response.ok) {
      console.log(response);
      return
    }

    console.log("success email");

  } catch(e){

    console.log("error");

  }
}

Here is my form code

<form onSubmit={submitForm}>
        <label>
          Name
          <input
            type="text"
            name="name"
            value={formState.name}
            onChange={onChange}
          />
        </label>
        <label>
          Email
          <input
            type="email"
            name="email"
            value={formState.email}
            onChange={onChange}
          />
        </label>
        <label>
          Subject
          <input
            type="text"
            name="subject"
            value={formState.subject}
            onChange={onChange}
          />
        </label>
        <div>
          <h3>Reasons for wanting to train</h3>
          <label>
          Weight Loss
          <input 
            type="checkbox"
            name="weightLoss"
            checked={formState.weightLoss}
            onChange={onChange}
          />
        </label>
        </div>

        <label>
          message
          <textarea
            name="message"
            value={formState.message}
            onChange={onChange}
          />
        </label>
        <button type="submit">Submit</button>
      </form>

In your change handler, detect if it's a checkbox that is not checked, then set the state accordingly:

if (e.target.type === 'checkbox' && !e.target.checked) {
    setFormState({...formState, [e.target.name]: ''});
} else {
    setFormState({...formState, [e.target.name]: e.target.value });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM