1.0.2 • Published 1 year ago

use-form-ts v1.0.2

Weekly downloads
2
License
ISC
Repository
github
Last release
1 year ago

useForm TypeScript Hook

This is a lightweight form style for someone who would normally do it all themselves but with some helping types.

Installation

yarn add use-form-ts

Getting Started

Use the hook to get started, we'll use useState for the state management in this example

const [formState, setFormState] = React.useState({
  firstname: "",
  lastname: "",
});
const form = useForm({
  values: state.formState,
  onChange: (value) => setFormState({ ...state, ...value }),
});

Form has two methods, one is validate, and the other is createFormItem.

Validate

We use validate in the submit handler typically

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  if (form.validate()) {
    // Perform some action here
  }
};

createFormItem

We use createFormItem for defining the variables that go in to our component.

{
  form.createFormItem("firstname", {
    adaptor: (e: React.ChangeEvent<HTMLInputElement>) => e.target.value,
    meta: {
      label: "First Name",
    },
    required: true,
  })(({ errorText, meta: { label }, ...props }) => (
    <InputField label={label} {...props} errorText={errorText || ""} />
  ));
}

adaptor is a conversion if necessary for the callbacks, as typically input elements will return you an event and not the actual value that changed.

meta is a convenience pass through object, the purpose is that it allows you to define reusable components, which can be configured declaratively, for example yaml, that generates the form schema that then generate the code for the form.

The rest of the options in createFormItem are validation options.

Validation options

  • required is a common method for highlighting that something needs to be entered
  • validationMessages is a object that allows overwriting the default messages for the built in validation params.
  • custom is a handler if you want to perform your own custom validation
  • customAsync is a handler for async custom validation
  • validation: is an object that defines some built in validation methods, these are:
    • whitespace is like required but ignores whitespace as well
    • email checks for a valid email
    • regex allows checking for any regex
1.0.2

1 year ago

1.0.1

2 years ago

0.0.17

3 years ago

0.0.18

3 years ago

0.0.19

3 years ago

0.0.16

3 years ago

0.0.15

3 years ago

0.0.14

3 years ago

0.0.13

3 years ago

0.0.10

3 years ago

0.0.12

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago