Reputation: 1545
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>
Upvotes: 1
Views: 6718
Reputation: 5566
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 });
}
Upvotes: 6