Skip to main content

Rendering forms

Forms are rendered using derivatives of the FormView component. This section describes how to work with that component and it's cousin, StatefulFormView.

Basic rendering

The most common way to render a form is through the <FormView> component.

The FormView component takes your form definition and the form data and renders it:

import React from "react";
import { textField, createForm, FormView } from "@fab4m/fab4m";

const form = createForm({
text: textField({ label: "Text field" }),
});

export default function BasicExample() {
return <FormView form={form} data={{ text: "Some text" }} />;
}

Managing the form state

The FormView component only renders the form with the data provided, and doesn't manage the form state. When using the FormView component you have to do that yourself:

import * as React from "react";
import { textField, createForm, FormView } from "@fab4m/fab4m";

const form = createForm({
text: textField({ label: "Text field" }),
});

export default function FormViewExampleWithHook() {
const [data, changeData] = React.useState({ text: "Some text" });
form.onDataChange(changeData);
return (
<div>
<FormView form={form} data={data} hideSubmit={true} />
<p>{data.text}</p>
</div>
);
}

Handling the state automatically

If you don't want to manage the state of the form yourself you can use our provided <StatefulFormView> component:

import * as React from "react";
import { textField, createForm, StatefulFormView } from "@fab4m/fab4m";

const form = createForm({
text: textField({ label: "Text field" }),
});

export default function StatefulFormExample() {
return <StatefulFormView form={form} />;
}

Defining forms inside React components

Creating the form definition is resource heavy, so if you need to define your form definition within your react component you should use the useForm() hook:

import * as React from "react";
import { textField, StatefulFormView, useForm, createForm } from "@fab4m/fab4m";

export default function HookExample() {
const form = useForm(() =>
createForm({ text: textField({ label: "text field" }) })
);
return <StatefulFormView form={form} />;
}

The useForm hook optionally takes an array of dependencies as it's second argument that will be checked, and the form will be rebuilt if any changes are detected.

Internally, the useForm hook is just a wrapper around a useMemo hook.