Create your form

Modular Forms consists of hooks, components and methods. To create a form you use the useForm hook.

Form hook

The useForm hook returns a tuple containing the store of the form in the first place and an object with the Form, Field and FieldArray component afterwards. You can use the store to access the state of the form and make changes to it using methods that will be introduced later.

import { useForm } from '@modular-forms/preact';

type LoginForm = {
  email: string;
  password: string;
};

export default function App() {
  const [loginForm, { Form, Field, FieldArray }] = useForm<LoginForm>();
}

Destructuring

You do not have to destructure the object with the components. In this way, the tuple allows you to freely name the two return values. This can be useful, for example, when a page contains multiple forms. Also, you can simply omit the first return value if you don't need it.

export default function App() {
  const [, Login] = useForm<LoginForm>();
  const [, Register] = useForm<RegisterForm>();

  return (
    <>
      <Login.Form></Login.Form>
      <Register.Form></Register.Form>
    </>
  );
}

Components

The returned Form, Field and FieldArray component are already connected with the store of your form. Also, if you are using TypeScript, they are aware of your fields and their data types, which gives you the benefit of type safety and autocompletion.

JSX code

In the JSX part of your component you start with the Form component. It encloses the fields of your form and through its properties you can define what happens when the form is submitted. More on this later.

import { useForm } from '@modular-forms/preact';

type LoginForm = {
  email: string;
  password: string;
};

export default function App() {
  const [loginForm, { Form, Field }] = useForm<LoginForm>();

  return <Form></Form>;
}