Skip to content

Instantly share code, notes, and snippets.

@andrew-codes
Last active November 8, 2021 19:49
Show Gist options
  • Save andrew-codes/2a3618d5a0226a143ee314c8c12acaa4 to your computer and use it in GitHub Desktop.
Save andrew-codes/2a3618d5a0226a143ee314c8c12acaa4 to your computer and use it in GitHub Desktop.
Idea for form family of components
// Format for a validation rule; many can be composed in different ways for more complex rules.
const isRequired = (message) => (value) => (value === '' || !value) ? message : false;
const [handleSubmit, handleReset] = useForm();
// Could optionally expose the formState in case of conditional rendering of fields.
// const [formState, ...] = useForm();
// or per field
// const [value, isValid, touched] = useForm('name');
// Form handles form's state; including data, validation, focus state (has a value been touched), etc.
<Form onReset={console.log} onSubmit={console.log}>
<SpacedGroup direction="vertical" xs={0}>
// Form.Field component takes a component (`as`) and injects already constructed form-enabled event handlers
// Handles the proper accessibility for a form field's label and control, error messaging, etc.
// `as` component API is:
// defaultValue, hintText, touched, valid, value, onBlur, onChange
<Form.Field name="name" label="Name" as={TextField} hintText="hint text" defaultValue="My Name" />
<Form.Field name="email" label="Email" as={TextField} hintText="validated email" validate={isRequired} />
<PrimaryButton onClick={handleSubmit}>
Submit
</PrimaryButton>
</SpacedGroup>
</Form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment