-
Notifications
You must be signed in to change notification settings - Fork 6
Home
Stijn Rogiest edited this page Feb 18, 2021
·
28 revisions
npm install --save typed-react-form
yarn add typed-react-form
Example of a simple type-checked form consisting of 2 fields, firstName
and lastName
.
When using FormInput
, it is required to pass the form as a prop, this is needed for type-checking.
import { useForm, FormInput } from "typed-react-form";
function BasicFormExample() {
// Use the useForm hook to create a new form state mananger. First parameter contains the default values.
const form = useForm({ firstName: "", lastName: "" });
return (
// Use normal form element
<form
onSubmit={(ev) => {
// Prevent the form from reloading the page
ev.preventDefault();
// form.values contains the form values
console.log("submit", form.values);
}}
>
{/* Use FormInput to create a type-checked and stateful <input />, make sure you pass form as a prop */}
{/* The name prop is type-checked! */}
<FormInput form={form} type="text" name="firstName" />
<FormInput form={form} type="text" name="lastName" />
{/* Triggers onSubmit when clicked */}
<button>Submit</button>
</form>
);
}
It is important to know that you shouldn't use useState
together with typed-react-form hooks and large forms, because a state change will rerender the whole form. This library is build upon the fact that only the things that change should rerender. This is what makes it very fast.
If you want custom state in a large form, you should take a look at custom form state.
Tweak the basic example to your desire! Find your next step here:
- Inputs
- Using Object fields
- Using Array fields
- Using validators
- Example: creating a submit button that disables when unmodified/error
- Example: creating a component which shows the current form values in JSON
- Usage with styled-components
- isSubmitting and custom form state
- Classes
- Hooks
- Components
- Form element components