Skip to content

Instantly share code, notes, and snippets.

@DveMac
Created December 5, 2020 12:42
Show Gist options
  • Save DveMac/c22b14a5a060c771a1dcd761ef409305 to your computer and use it in GitHub Desktop.
Save DveMac/c22b14a5a060c771a1dcd761ef409305 to your computer and use it in GitHub Desktop.
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