Your first form
A sign-up form with two inputs and a submit handler, and no plugins.
This is the form you’ll end up with. Fill it in and submit it.
Every page in Basics uses the adapter alone. No plugins, nothing registered.
Make a forms object
createForms holds what your forms share: plugins, field components and
settings. This form needs none of them.
import { createForms } from "@lunarhue/forms-react";
const forms = createForms();Define the form
const signUp = forms.define({
defaultValues: { name: "", email: "" },
onSubmit: (value) => `Signed up ${value.name}.`,
});defaultValues is the value the form starts from, and its type is the form’s
type. Here that is { name: string; email: string }. onSubmit gets a copy
of the value when the user submits.
Render it
useForm makes a form from the definition for this component.
import { inputProps, useForm } from "@lunarhue/forms-react";
export default function SignUpForm() {
const form = useForm(signUp);
return (
<form.Form>
{(formProps) => (
<form {...formProps}>
<form.Field name="name">
{(field) => (
<label>
Name
<input {...inputProps(field)} />
</label>
)}
</form.Field>
<form.Field name="email">
{(field) => (
<label>
Email
<input {...inputProps(field, { type: "email" })} />
</label>
)}
</form.Field>
<button type="submit">Sign up</button>
</form>
)}
</form.Form>
);
}form.Formhands your<form>its submit handler asformProps, and turns off the browser’s own validation.form.Fieldtakes a field name and passes that field to its child. The compiler checks the name, soname="emial"is a type error.inputProps(field)gives the input its value,name,id, the change and blur handlers, and the aria attributes for errors.
Show the result
Whatever onSubmit returns becomes submission.result. Read it from the
form’s state:
<form.State select={(state) => state.submission}>
{(submission) => (
<p role="status">{submission.status === "succeeded" ? submission.result : null}</p>
)}
</form.State>form.State re-renders only its children, and only when the selected value
changes.
A submission is idle, submitting, invalid, failed or succeeded. If
onSubmit throws, the status is failed and error holds what it threw.
Submit has the rest.
Next
The form takes anything right now. Validation adds the checks.
Last updated