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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With