This is a lightweight form style for someone who would normally do it all themselves but with some helping types.
yarn add use-form-tsUse 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.
We use validate in the submit handler typically
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (form.validate()) {
// Perform some action here
}
};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.
requiredis a common method for highlighting that something needs to be enteredvalidationMessagesis a object that allows overwriting the default messages for the built in validation params.customis a handler if you want to perform your own custom validationcustomAsyncis a handler for async custom validationvalidation: is an object that defines some built in validation methods, these are:whitespaceis like required but ignores whitespace as wellemailchecks for a valid emailregexallows checking for any regex