Skip to content
forms

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.

bun add @lunarhue/forms-solidnpm install @lunarhue/forms-solidpnpm add @lunarhue/forms-solidyarn add @lunarhue/forms-solid

Make a forms object

createForms holds what your forms share: plugins, field components and settings. This form needs none of them.

sign-up.tsx
import { createForms } from "@lunarhue/forms-solid";

const forms = createForms();

Define the form

sign-up.tsx
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

createForm makes a form from the definition for this component.

sign-up.tsx
import { createForm, inputProps } from "@lunarhue/forms-solid";

export default function SignUpForm() {
  const form = createForm(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.Form hands your <form> its submit handler as formProps, and turns off the browser’s own validation.
  • form.Field takes a field name and passes that field to its child. The compiler checks the name, so name="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:

<p role="status">
  <Show when={form.state.submission.status === "succeeded" && form.state.submission}>
    {(submission) => submission().result}
  </Show>
</p>

form.state is reactive, so only this text updates.

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