Skip to content
Stijn Rogiest edited this page Feb 19, 2021 · 28 revisions

Getting started

Welcome to the typed-react-form documentation!

Step 1: Install

Begin by installing the package into your React project:

npm install --save typed-react-form
yarn add typed-react-form

Step 2: Basic form setup

A form always starts with the useForm hook call, this function returns a form, which you must then give to all your inputs (this is required for type-checking).

All of the form hook (useForm, useChildForm ...) must be called, unconditionally, at the start of your component, just like the normal React hooks.

import { useForm } from "typed-react-form";

function MyForm() {
    const form = useForm();
}

Example of a simple type-checked form consisting of 2 fields, firstName and lastName.

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>
    );
}

Step 3: It's your turn

Tweak the basic example to your desire! Find your next step here:

Reference

Clone this wiki locally