Created
December 5, 2020 12:42
-
-
Save dmaevac/c22b14a5a060c771a1dcd761ef409305 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SimpleForm = ({ onSubmit }) => { | |
// We use useState hook to store the forms data | |
const [formState, setFormState] = useState({ | |
name: '', | |
address: '', | |
pet: '', | |
}); | |
// a function to handle the form submission | |
const handleSubmit = (ev) => { | |
ev.preventDefault(); | |
onSubmit(formState); | |
}; | |
// finally, a function that is called when any of our inputs change, wrapped | |
// in useCallback for, you know, performance | |
const updateField = useCallback((ev) => { | |
const { name, value } = ev.currentTarget; | |
setFormState((current) => ({ ...current, [name]: value })); | |
}, []); | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input type="text" value={formState.name} name="name" onChange={updateField} /> | |
<input type="text" value={formState.address} name="address" onChange={updateField} /> | |
<select value={formState.pet} onChange={updateField} name="pet"> | |
<option value="dog">Dog</option> | |
<option value="cat">Cat</option> | |
<option value="fish">Fish</option> | |
</select> | |
<input type="submit" value="Save" /> | |
</form> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment