Skip to content

Instantly share code, notes, and snippets.

@tmazeika
Last active June 19, 2023 07:27
Show Gist options
  • Save tmazeika/39f3401130f68b1c686c95cb622af957 to your computer and use it in GitHub Desktop.
Save tmazeika/39f3401130f68b1c686c95cb622af957 to your computer and use it in GitHub Desktop.
import React from 'react';
import useForm, { FormValueController } from './useForm';
function App(): JSX.Element {
const form = useForm({
initialValues: {
name: '',
email: '',
},
onValidate(values, errors) {
// Setting at least one error here will prevent `onSubmit` from being
// called.
if (values.name === '') errors.name = 'Name cannot be empty.';
if (values.email === '') errors.email = 'Email cannot be empty.';
},
// Can be async! With async, `form.isSubmitting` will be true until the
// promise resolves. Without async, `form.isSubmitting` never turns to true.
onSubmit(values) {
alert(`Submitting name=${values.name} email=${values.email}`);
},
});
return (
<form onSubmit={form.onSubmit}>
<input
placeholder="Name"
value={form.values.name}
// Note that 'name' type checks and cannot be anything other than 'name'
// or 'email'.
onChange={(e) => form.set('name', e.target.value)}
/>
{/* Check for a name error and display it if it's not undefined. */}
{form.errors.name && (
<p>{form.errors.name}</p>
)}
{/* Use `form.control()` to create a controller for a specific form value
that can get or set that value. */}
<EmailInput controller={form.control('email')}/>
{form.errors.email && (
<p>{form.errors.email}</p>
)}
<input type="submit" value="Submit" disabled={form.isSubmitting}/>
<input type="reset" value="Reset" onClick={form.reset}/>
</form>
);
}
interface EmailInputProps {
/** A controller that gets and sets the value of this email input field. */
controller: FormValueController<string>;
}
function EmailInput(props: EmailInputProps): JSX.Element {
return (
<input
placeholder="Email"
value={props.controller.value}
onChange={(e) => props.controller.set(e.target.value)}
/>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment