react-forms-hook
A small and simple way to deal with Forms in React, looks a bit like formik, but much much simpler.
Installation
$ yarn add @ethicdevs/react-forms-hook
# or
$ npm i @ethicdevs/react-forms-hook
Usage
This example is made with react-native
components (i.e. View
) but this lib also works with regular react
apps!
import React, { FC } from "react";
import { TextInput, View } from "react-native";
import { Form, useForm } from "@ethicdevs/react-forms-hook";
type MyScreenFormValues = {
foo: string;
bar: string;
baz: string;
quxx: string;
};
const FORM_ID = "my-super-form";
const MyScreenWithAForm: FC = () => {
const { registerField, handleSubmit } = useForm<MyScreenFormValues>(FORM_ID);
const onFormSubmit = (_, formValues) => {
console.log("Form was submitted:");
console.table(formValues);
};
return (
<View>
<Form id={FORM_ID}>
{/* Foo */}
<TextInput
label={"Foo:"}
placeholder={"Enter value for foo..."}
{...registerField("foo", {
nextField: "bar",
})}
/>
{/* Bar */}
<TextInput
label={"Bar:"}
placeholder={"Enter value for bar..."}
{...registerField("bar", {
nextField: "baz",
})}
/>
{/* Baz */}
<TextInput
label={"Baz:"}
placeholder={"Enter value for baz..."}
{...registerField("baz", {
nextField: "quxx",
})}
/>
{/* Quxx */}
<TextInput
label={"Quxx:"}
placeholder={"Enter value for quxx..."}
{...registerField("quxx", {
returnKeyType: "done",
returnSubmitsForm: true,
})}
/>
{/* Submit button */}
<Button text={"Submit form"} onPress={handleSubmit(onFormSubmit)} />
</Form>
</View>
);
};
Configuration
The useForm
hook and the Form
components both accepts an id
argument/property in order to support multi-forms.
The useForm
hook also takes some options:
opts.nextField
: Default: undefined. If set to an input name, on input submit (keyboard return key in react-native, enter key in react/browser) the specified field will be focused.opts.returnKeyType
: Default: 'next'. React Native specific, allows to set the keyboard return key type.opts.returnSubmitsForm
: Default: false. If set to true, when last input gets submitted then it will call the form submit handler (set during the useForm()#handleSubmit
execution on first render).
License
MIT